在我的应用程序中,我有一些代码可以在URL
中获取主机的范围。看起来像这样:
private func rangeOfHost(text: String) -> NSRange? {
let url = URL(string: text)
if let host: String = url?.host {
if let range = text.range(of: host) {
return NSRange(location: range.lowerBound.encodedOffset,
length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset)
}
}
return nil
}
Xcode一直警告我'encodedOffset' is deprecated: encodedOffset has been deprecated as most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.
。但是,我不清楚如何用这些建议替换那些encodingOffsets。有什么想法吗?
答案 0 :(得分:2)
从NSRange
创建Range<String.Index>
的简单正确的方法是使用其初始化程序:
public init<R, S>(_ region: R, in target: S) where R : RangeExpression, S : StringProtocol, R.Bound == String.Index
在您的情况下:
if let range = text.range(of: host) {
return NSRange(range, in: text)
}
答案 1 :(得分:-1)
yourIndex.utf16Offset(in: yourString)