How can I convert NSRange
to Range
in Swift?
I want to use the following UITextFieldDelegate
method:
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 = "