distance(from:to:)' is unavailable: Any String

2020-03-12 09:56发布

问题:

I was trying to migrate my app to Swift 4, Xcode 9. I get this error. Its coming from a 3rd party framework.

distance(from:to:)' is unavailable: Any String view index conversion can fail in Swift 4; please unwrap the optional indices

func nsRange(from range: Range<String.Index>) -> NSRange {
    let utf16view = self.utf16
    let from = range.lowerBound.samePosition(in: utf16view)
    let to = range.upperBound.samePosition(in: utf16view)
    return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from), // Error: distance(from:to:)' is unavailable: Any String view index conversion can fail in Swift 4; please unwrap the optional indices
                       utf16view.distance(from: from, to: to))// Error: distance(from:to:)' is unavailable: Any String view index conversion can fail in Swift 4; please unwrap the optional indices
}

回答1:

You can simply unwrap the optional indices like this:

func nsRange(from range: Range<String.Index>) -> NSRange? {
    let utf16view = self.utf16
    if let from = range.lowerBound.samePosition(in: utf16view), let to = range.upperBound.samePosition(in: utf16view) {
       return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from), utf16view.distance(from: from, to: to))
    }
    return nil
}


回答2:

The error says that the distances you are generating are optionals and need to be unwrapped. Try this:

func nsRange(from range: Range<String.Index>) -> NSRange {
    let utf16view = self.utf16
    guard let lowerBound = utf16view.distance(from: utf16view.startIndex, to: from), let upperBound = utf16view.distance(from: from, to: to) else { return NSMakeRange(0, 0) }
    return NSMakeRange(lowerBound, upperBound)
}

However the return could be handled better in the guard statement. I'd recommend making the return type of the function NSRange? and checking for nil wherever you call the function to avoid inaccurate values being returned.



回答3:

Please check :

let dogString = "Dog‼              
                            
标签: swift swift4