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?
You have to explicitly bridge (cast) String
to NSString
:
(string as NSString).characterAtIndex(0)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With