I'm writing a validator for a UITextField, I'm given an existing string, replacement string and an NSRange where the replacement takes place. I have two versions of my code to get the new candidate string:
a. Explicitly use NSString
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let existingString: NSString = textField.text ?? ""
let candidateString = existingString.stringByReplacingCharactersInRange(range, withString: string)
//do validation on candidateString here
return true
}
b. Generate a Range<String.Int>
and use it on Swift String's stringByReplacingCharactersInRange
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let existingString = textField.text ?? ""
let swiftRange = advance(existingString.startIndex, range.length)..<advance(existingString.startIndex, range.length) // I hate this.
let candidateString = existingString.stringByReplacingCharactersInRange(swiftRange, withString: string)
So putting aside the fact that the code to generate the Swift range is unreadable... do these two approaches differ in execution. Specifically does Swift have a better (probably more unicode savvy) version of stringByReplacingCharactersInRange
which I get by avoiding the conversion to NSString?