How can I convert NSRange
to Range
in Swift?
I want to use the following UITextFieldDelegate
method:
I've found the cleanest swift2 only solution is to create a category on NSRange:
extension NSRange {
func stringRangeForText(string: String) -> Range {
let start = string.startIndex.advancedBy(self.location)
let end = start.advancedBy(self.length)
return Range(start: start, end: end)
}
}
And then call it from for text field delegate function:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let range = range.stringRangeForText(textField.text)
let output = textField.text.stringByReplacingCharactersInRange(range, withString: string)
// your code goes here....
return true
}