我有一个将字符类型转换为字符串类型的问题.首先,我在String的扩展名下面用于在String中查找第n个字符.
extension String {
func characterAtIndex(index: Int) -> Character? {
var cur = 0
for char in self {
if cur == index {
return char
}
cur++
}
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了这个类扩展我想要的东西.但是,当我将第n个字符用于我的自定义UIButton的标题时,会出错.我的Uibutton课程是
class hareketliHarfler: UIButton {
init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
}
func getLetter(letter:String!){
self.titleLabel.text = letter
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试访问"getLetter(letter:String)"函数时出现错误.以下是主视图控制器代码的示例:
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) ****
Run Code Online (Sandbox Code Playgroud)
在*部分我尝试.getLetter(bufi),. getLetter(bufi as String)我也尝试更改函数的参数类型.看起来像:func getLetter(letter:Character!)或func getLetter(letter:AnyObject!)......等找不到方法.需要帮助.谢谢
Mat*_*son 52
你的问题很简单:你的characterAtIndex函数返回一个Character,self.titleLabel.text是一个String.你不能隐式地在两者之间进行转换.最简单的方法是使用String初始化器将Character转换为String:
// 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.
}
Run Code Online (Sandbox Code Playgroud)
与其他解决方案不同,这对于不常见的Unicode字符是安全的,并且不会初始化潜在的大型数组或迭代整个String以获取第三个字符.
| 归档时间: |
|
| 查看次数: |
46597 次 |
| 最近记录: |