Swift3 NSRange与range相互转化

//NSRange转化为range

extension String {    func ToRange(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

   }

}

//range转换为NSRangeextension 

String {    func ToNSRange(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))

   }

}


Swift3 NSRange与range相互转化_第1张图片

你可能感兴趣的:(Swift3 NSRange与range相互转化)