“String”类型的值没有成员'characterAtIndex'

时间:2021-05-16 17:06:48

I'm using the following UITextFieldDelegate method:

我正在使用以下UITextFieldDelegate方法:

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:

我不知道这段代码有什么问题,因为NSString类引用列出了这个函数:

func characterAtIndex(_ index: Int) -> unichar

Do you know what I am doing wrong?

你知道我做错了什么吗?

2 个解决方案

#1


5  

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

您必须显式桥接(强制转换)String到NSString:

(string as NSString).characterAtIndex(0)

#2


2  

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.

虽然Swift的String和NSString是可以互换的,但是你可以将String传递给期望NSString的API,反之亦然,这两者并不相同。通常,如果没有强制转换,则无法在String上调用NSString方法。

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

从String获取初始字符的方式是不同的 - 而不是使用您调用的characterAtIndex(0)

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

or

let initialChar = str.characters.first // produces an optional value

#1


5  

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

您必须显式桥接(强制转换)String到NSString:

(string as NSString).characterAtIndex(0)

#2


2  

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.

虽然Swift的String和NSString是可以互换的,但是你可以将String传递给期望NSString的API,反之亦然,这两者并不相同。通常,如果没有强制转换,则无法在String上调用NSString方法。

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

从String获取初始字符的方式是不同的 - 而不是使用您调用的characterAtIndex(0)

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

or

let initialChar = str.characters.first // produces an optional value