3

I'm trying to add an initializer to Range.

import Foundation

extension Range {
    init(_ range: NSRange, in string: String) {
        let lower = string.index(string.startIndex, offsetBy: range.location)
        let upper = string.index(string.startIndex, offsetBy: NSMaxRange(range))
        self.init(uncheckedBounds: (lower: lower, upper: upper))
    }
}

But, the last line has a Swift compiler error.

Cannot convert value of type '(lower: String.Index, upper: String.Index)' (aka '(lower: String.CharacterView.Index, upper: String.CharacterView.Index)') to expected argument type '(lower: _, upper: _)'

How do I get it to compile?

1

3 Answers 3

1

The problem is even though String.Index does conform to Comparable protocol, you still need to specify the Range type you want to work with public struct Range<Bound> where Bound : Comparable {}

Note: As NSString uses UTF-16, check this and also in the link you've referred to, your initial code does not work correctly for characters consisting of more than one UTF-16 code point. The following is the updated working version for Swift 3.

 extension Range where Bound == String.Index {
    init(_ range: NSRange, in string: String) {
        let lower16 = string.utf16.index(string.utf16.startIndex, offsetBy: range.location)
        let upper16 = string.utf16.index(string.utf16.startIndex, offsetBy: NSMaxRange(range))

        if let lower = lower16.samePosition(in: string),
            let upper = upper16.samePosition(in: string) {
            self.init(lower..<upper)
        } else {
            fatalError("init(range:in:) could not be implemented")
        }
    }
}

let string = "❄️Let it snow! ☃️"

let range1 = NSRange(location: 0, length: 1)
let r1 = Range<String.Index>(range1, in: string) // ❄️

let range2 = NSRange(location: 1, length: 2)
let r2 = Range<String.Index>(range2, in: string) // fatal error: init(range:in:) could not be implemented

To answer the OP's comment: The problem is an NSString object encodes a Unicode-compliant text string, represented as a sequence of UTF–16 code units. Unicode scalar values that make up a string’s contents can be up to 21 bits long. The longer scalar values may need two UInt16 values for storage.

Therefore, some letters like ❄️ takes up two UInt16 values in NSString but only one in String. As you pass an NSRange argument to the initializer, you may expect it to work correctly in NSString.

In my example, the results for r1 and r2 after you convert string to utf16 are '❄️' and a fatal error. Meanwhile, the results from your original solution are '❄️L' and 'Le', respectively. Hopefully, you see the difference.

In case you insist with the solution without converting to utf16, you can take a look at the Swift source code to make decision. In Swift 4, you will have the initializer as a built-in lib. The code is as follows.

extension Range where Bound == String.Index {
  public init?(_ range: NSRange, in string: String) {
    let u = string.utf16
    guard range.location != NSNotFound,
      let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex),
      let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex),
      let lowerBound = String.Index(start, within: string),
      let upperBound = String.Index(end, within: string)
    else { return nil }

    self = lowerBound..<upperBound
  }
}
3
  • I don't understand why you need to use a UTF-16 encoding of string. My initial code seems to work correctly, even for strings with emojis. Please provide a counter example.
    – ma11hew28
    Aug 1, 2017 at 4:05
  • It would be a very long comment to answer you question so I decide to update my answer. I also edited my example a bit to make the difference more obvious.
    – Lawliet
    Aug 1, 2017 at 9:52
  • Well, sure, I see the difference, but I still don't understand why the results in your example are correct. I guess I'll take Apple's word for it. Thank you! :-)
    – ma11hew28
    Aug 2, 2017 at 4:49
1

You need to constrain your range initializer to where Bound is equal to String.Index, get your NSRange utf16 indexes and find the same position of the string index in your string as follow:

extension Range where Bound == String.Index {
    init?(_ range: NSRange, in string: String) {
        guard
            let start = string.utf16.index(string.utf16.startIndex, offsetBy: range.location, limitedBy: string.utf16.endIndex),
            let end = string.utf16.index(string.utf16.startIndex, offsetBy: range.location + range.length, limitedBy: string.utf16.endIndex),
            let startIndex = start.samePosition(in: string),
            let endIndex = end.samePosition(in: string)
        else {
            return nil
        }
        self = startIndex..<endIndex
    }
}
0
0

The signature for that method requires a "Bound" type (at least in swift 4)

Since Bound is just an associated type of "Comparable" and String.Index conforms to it, you should just be able to cast it.

extension Range {
    init(_ range: NSRange, in string: String) {
        let lower : Bound = string.index(string.startIndex, offsetBy: range.location) as! Bound
        let upper : Bound = string.index(string.startIndex, offsetBy: NSMaxRange(range)) as! Bound

        self.init(uncheckedBounds: (lower: lower, upper: upper))
    }
}

https://developer.apple.com/documentation/swift/rangeexpression/2894257-bound

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.