encodedOffset弃用

问题描述 投票:3回答:2

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

swift string nsrange
2个回答
4
投票

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
投票
yourIndex.utf16Offset(in: yourString)
© www.soinside.com 2019 - 2024. All rights reserved.