blueball blueball - 1 year ago 186
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 Source

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

(string as NSString).characterAtIndex(0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download