美文网首页理论
Swift3.0 NSRange与Range的相互转换

Swift3.0 NSRange与Range的相互转换

作者: 宁静1致远 | 来源:发表于2016-11-16 14:47 被阅读2410次

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

//range转换为NSRange
extension String {
    func nsRange(from range: Range<String.Index>) -> 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<String.Index>? {
        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
    }
}

相关文章

网友评论

  • o_Cooper_o:Use of unresolved identifier 'utf16' 报警时怎么回事

本文标题:Swift3.0 NSRange与Range的相互转换

本文链接:https://www.haomeiwen.com/subject/hzrrpttx.html