问题描述
我正在创建一个简单的计算器应用程序,目前正在努力删除我的按钮被点击时的最后一个字符。我正在使用 dropLast()
方法,但我一直收到错误
I'm creating a simple calculator app and currently struggling at deleting the last character when a my button is tapped. I'm using the dropLast()
method but I keep getting the error
@IBAction func onDelPressed (button: UIButton!) {
runningNumber = runningNumber.characters.dropLast()
currentLbl.text = runningNumber
}
推荐答案
Swift 4(附录)
在Swift中,您可以申请 dropLast ()
直接在 String
实例上,不再调用 .characters
来访问
:字符串的
字符串
Swift 4 (Addendum)
In Swift, you can apply dropLast()
directectly on the String
instance, no longer invoking .characters
to access a CharacterView
of the String
:
var runningNumber = "12345"
runningNumber = String(runningNumber.dropLast())
print(runningNumber) // 1234
Swift 3(原始答案)
我假设 runningNumber
是一个 String
实例。在这种情况下, runningNumber.characters.dropLast()
的类型不是 String
,而是 CharacterView
:
Swift 3 (Original answer)
I'll assume runningNumber
is a String
instance. In this case, runningNumber.characters.dropLast()
is not of type String
, but a CharacterView
:
let foo = runningNumber.characters.dropLast()
print(type(of: foo)) // CharacterView
你需要使用 CharacterView
实例化 String
实例,然后将其分配回类型 String
的属性,例如
You need to use the CharacterView
to instantiate a String
instance prior to assigning it back to a property of type String
, e.g.
var runningNumber = "12345"
runningNumber = String(runningNumber.characters.dropLast())
print(runningNumber) // 1234
即你的情况
@IBAction func onDelPressed (button: UIButton!) {
runningNumber = String(runningNumber.characters.dropLast())
currentLbl.text = runningNumber
}
这篇关于删除Swift 3中的最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!