在我的应用程序中,我有一些代码来获取中的主机范围URL。看起来像这样:
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 the most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.。但是,我不清楚如何用这些建议替换那些encodingOffsets。有任何想法吗?
'encodedOffset' is deprecated: encodedOffset has been deprecated as the most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.
一个简单而建立一个正确的方式NSRange从Range<String.Index>是使用它的初始化:
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) }