Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

nsstring

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?

like image 506
blueball Avatar asked Jun 19 '16 09:06

blueball


2 Answers

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

(string as NSString).characterAtIndex(0)
like image 61
Kirsteins Avatar answered Nov 15 '22 08:11

Kirsteins


Although Swift's String and NSString are interchangeable, in the sense that you can pass String to APIs expecting NSString and vice versa, the two are not the same. Generally, you cannot call NSString methods on String without a cast.

The way you get the initial character from String is different - rather than using characterAtIndex(0) you call

let str = "Hello"
let initialChar = str[str.startIndex] // will throw when str is empty

or

let initialChar = str.characters.first // produces an optional value
like image 22
Sergey Kalinichenko Avatar answered Nov 15 '22 09:11

Sergey Kalinichenko