Swift字符串操作不起作用
问题描述:
我想从标签中读取字符串并删除它的最后一个字符。Swift字符串操作不起作用
这是我正在尝试:
@IBAction func del(sender: UIButton) {
let str = telephone.text!;
let newstr = str.remove(at: str.index(before: str.endIndex))
telephone.text = newstr;
}
当我跑,我得到一个错误:
"String" does not have a member named "remove"
有人可以帮我找出这个问题? 刚开始学习迅速:(
答
remove(at:)
变异的接收器,因此它必须是一个可变 字符串:
var str = telephone.text!
str.remove(at: str.index(before: str.endIndex))
telephone.text = str
或者使用substring(to:)
,返回新字符串 不是修改接收机:
let str = telephone.text!
let newstr = str.substring(to: str.index(before: str.endIndex))
telephone.text = newstr
+0
谢谢,这也工作:) – ssdesign
答
您可以使用:
let idx = str.index(before: str.endIndex) // compute the index
let s = str.substring(to: idx) // get the substring
答
remove
定义如下:
public mutating func remove(at i: String.Index) -> Character
参见mutating
改性剂?这意味着它会调用调用该方法的实例。在你的情况下,实例是str
,一个常量。由于常量不能被突变,所以代码不能编译。
而且由于remove
返回删除的字符,
let newstr = str.remove(at: str.index(before: str.endIndex))
这里newstr
不会存储与删除的最后一个字符的字符串。
你应该重写方法是这样的:
telephone.text!.remove(at: telephone.text!.index(before: telephone.text!.endIndex))
在游乐场我可以编译你的代码,并预期它会成功。尝试使用'let str =“Test”'进行测试。顺便说一句,你不需要在行尾使用';'。 – LinusGeffarth
我尝试了“东西”作为文本和IDE仍然给出了同样的错误:( – ssdesign
'删除(在:))突变接收器,并期望一个*变量* –