mosaic6
mosaic6

Reputation: 933

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

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
}

Upvotes: 18

Views: 11065

Answers (2)

Dilip
Dilip

Reputation: 369

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)
        // ...
    }
    // ...
}

Upvotes: -1

matt
matt

Reputation: 536037

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

var newString = (text! as NSString).stringByReplacingCharactersInRange(range, withString: string) as? NSString

Upvotes: 34

Related Questions