encodedOffset deprecation

此生再无相见时 提交于 2019-11-28 00:57:27

问题


In my application, I have some code to fetch the range of the host in a URL. It looks like this:

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 has been warning me that 'encodedOffset' is deprecated: encodedOffset has been deprecated as the most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.. However, it's not clear to me how I can replace those encodedOffsets with these suggestions. Any ideas?


回答1:


A simple and correct way to create an NSRange from a Range<String.Index> is to use its initializer:

public init<R, S>(_ region: R, in target: S) where R : RangeExpression, S : StringProtocol, R.Bound == String.Index

In your case:

if let range = text.range(of: host) {
    return NSRange(range, in: text)
}



回答2:


yourString1.yourIndex.utf16Offset(in: yourString2)


来源:https://stackoverflow.com/questions/55588210/encodedoffset-deprecation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!