Cannot convert value of type 'NSRange' (aka '_NSRange') to expected type 'Range<Index>'(aka 'Range<String.CharacterView.Index>')
Asked Answered
U

2

18

Getting this error when checking the range for string characters...

@objc func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let shouldChange = false
    let text = textField.text
    var newString = text!.stringByReplacingCharactersInRange(range, withString: string) as? NSString
    if newString.length > 14{
        newString = newString.substringToIndex(14)
    }
    textField.text = newString.uppercaseString

    return shouldChange
}
Underplot answered 24/9, 2015 at 19:49 Comment(1)
Compare NSRange to Range<String.Index>.Algonquin
D
34

Instead of text! say (text! as NSString).

var newString = (text! as NSString).stringByReplacingCharactersInRange(range, withString: string) as? NSString
Densmore answered 24/9, 2015 at 19:54 Comment(0)
P
-1

Swift 4

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

    if let oldString = textField.text {
        let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!,
                                                      with: string)
        // ...
    }
    // ...
}
Padron answered 26/9, 2018 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.