Swift将字符转换为字符串 [英] Swift Converting Character to String
问题描述
我将字符类型转换为字符串类型时遇到问题。首先,我在String的下面扩展,用于在String中查找第n个字符。
I have an issue with converting character type to String type. First of all, I have below extension of String for finding nth character within String.
extension String {
func characterAtIndex(index: Int) -> Character? {
var cur = 0
for char in self {
if cur == index {
return char
}
cur++
}
return nil
}
}
我得到了我想要的东西这个类扩展。但是,当我将第n个字符用于我的自定义UIButton的标题时,会出错。我的Uibutton类是
I get what I want with this class extension. However when I use that nth character for title of my custom UIButton, gives an error. My Uibutton Class is
class hareketliHarfler: UIButton {
init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
}
func getLetter(letter:String!){
self.titleLabel.text = letter
}
}
当我尝试访问getLetter(letter:String)函数时显示错误。以下是主视图控制器代码的示例:
The error show when i try to access "getLetter(letter:String)" function. Here is example of main view Controller codes:
var harfim = hareketliHarfler(frame: CGRectMake(100,100,100,100))
var str="This is my String"
var bufi=str.characterAtIndex(3)
harfim.getLetter(bufi as AnyObject) ****
在 * 部分我尝试.getLetter(bufi),. getLetter(bufi as String)我也尝试更改参数类型的函数。看起来像:func getLetter(letter:Character!)或func getLetter(letter:AnyObject!)... etc
没找到方法。需要帮助。谢谢
In * section I try .getLetter(bufi), .getLetter(bufi as String) also I try to change parameter type of function. Look like: func getLetter(letter:Character!) or func getLetter(letter:AnyObject!)...etc Didn't find a way. Need a help on that. Thank you
推荐答案
你的问题非常简单:你的characterAtIndex函数返回一个Character,self.titleLabel.text是一个String。你无法隐式地在两者之间进行转换。最简单的方法是使用String初始化器将Character转换为String:
Your problem is quite simple: your characterAtIndex function returns a Character, and self.titleLabel.text is a String. You can't convert between the two implicitly. The easiest way would be to turn the Character into a String using the String initialiser:
// ch will be Character? type.
if let ch = str.characterAtIndex(3) {
// Initialise a new String containing the single character 'ch'
harfim.getLetter(String(ch))
} else {
// str didn't have a third character.
}
与其他解决方案不同,这对于不寻常的Unicode字符是安全的,并且不会初始化一个可能很大的数组或迭代整个String只是为了得到第三个字符。
Unlike other solutions, this is safe for unusual Unicode characters, and won't initialise a potentially large array or iterate the whole String just to get the third character.
这篇关于Swift将字符转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!