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

后端 未结 3 511
死守一世寂寞
死守一世寂寞 2021-01-11 23:51

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

相关标签:
3条回答
  • 2021-01-12 00:30

    Please check :

    let dogString = "Dog‼                                                                    
    0 讨论(0)
  • 2021-01-12 00:42

    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.

    0 讨论(0)
  • 2021-01-12 00:46

    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
    }
    
    0 讨论(0)
提交回复
热议问题