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

mosaic6 picture mosaic6 · Sep 24, 2015 · Viewed 10.2k times · Source

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
}

Answer

matt picture matt · Sep 24, 2015

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

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