Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encodedOffset deprecation

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?

like image 605
user4992124 Avatar asked Apr 09 '19 08:04

user4992124


2 Answers

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)
}
like image 144
Martin R Avatar answered Nov 18 '22 08:11

Martin R


yourString1.yourIndex.utf16Offset(in: yourString2)
like image 2
Hiren Panchal Avatar answered Nov 18 '22 07:11

Hiren Panchal