NSRange to Range

前端 未结 13 1232
失恋的感觉
失恋的感觉 2020-11-22 11:59

How can I convert NSRange to Range in Swift?

I want to use the following UITextFieldDelegate method:

13条回答
  •  死守一世寂寞
    2020-11-22 12:23

    Here's my best effort. But this cannot check or detect wrong input argument.

    extension String {
        /// :r: Must correctly select proper UTF-16 code-unit range. Wrong range will produce wrong result.
        public func convertRangeFromNSRange(r:NSRange) -> Range {
            let a   =   (self as NSString).substringToIndex(r.location)
            let b   =   (self as NSString).substringWithRange(r)
    
            let n1  =   distance(a.startIndex, a.endIndex)
            let n2  =   distance(b.startIndex, b.endIndex)
    
            let i1  =   advance(startIndex, n1)
            let i2  =   advance(i1, n2)
    
            return  Range(start: i1, end: i2)
        }
    }
    
    let s   =   "

提交回复
热议问题