Swift3.0 NSRange与Range的相互转换

swift中Range和NSRange用法有很大的区别,一些时候需要转换下面提供转换的方法

//range转换为NSRange
extension String {
    func nsRange(from range: Range) -> NSRange {
        let from = range.lowerBound.samePosition(in: utf16)
        let to = range.upperBound.samePosition(in: utf16)
        return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
                       length: utf16.distance(from: from, to: to))
    }
}
//NSRange转化为range
extension String {
    func range(from nsRange: NSRange) -> Range? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
            let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self)
            else { return nil }
        return from ..< to
    }
}

你可能感兴趣的:(Swift3.0 NSRange与Range的相互转换)