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

后端 未结 3 515
死守一世寂寞
死守一世寂寞 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:42

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

    func nsRange(from range: Range) -> 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.

提交回复
热议问题