blueball blueball - 5 months ago 49
Swift Question

Value of type 'String' has no member 'characterAtIndex'

I'm using the following UITextFieldDelegate method:

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


and get the error-message above when trying to access the first character:

let firstChar = string.characterAtIndex(0)


I don't know what's wrong with this code, since the NSString class reference lists the function:

func characterAtIndex(_ index: Int) -> unichar


Do you know what I am doing wrong?

Answer

You have to explicitly bridge (cast) String to NSString:

(string as NSString).characterAtIndex(0)