我有一种情况,URL
我可以在API响应中使用的旧属性具有不正确的子域。
例如,https://profiles.foobar.com
实际上应该是https://profiles-v2.foobar.com
对于URL
我收到的所有旧版文件,这都是相同的,需要将子域更新为-v2
。
数据最终将得到更正,但是现在我必须支持旧格式和新格式,因此在更新之前应检查是否错误。
我想编写一个简单的辅助函数,如果不正确,可以在模型中使用更新的prop替换子域。
现在,我在每个模型中都具有此功能,但是对于每个可能的子域,它实际上都是重复的,并且在每个模型中都存在。
private func mapV2ProfileDomain(_ url: URL?) -> URL? {
guard let urlString = url?.absoluteString else { return nil }
let mappedString = urlString.replacingOccurrences(of: "https://profiles.", with: "https://profiles-v2.")
return URL(string: mappedString)
}
使用Regex可以实现吗?
您实际上已经在使用正确的方法,replacingOccurrences
可以通过将options
参数设置为来使用正则表达式.regularExpression
let str2 = str.replacingOccurrences(
of: #"https://(\w*)\."#,
with: "https://$1-v2.",
options: .regularExpression
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句