在我的应用程序中,我有一些代码来获取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.
。但是,我不清楚如何用这个建议替换那些编码的偏移。有任何想法吗?
从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)
}
yourIndex.utf16Offset(in: yourString)