IBAction func numberPressed(sender: AnyObject) {
if isTyping == false {
firstNumber = (sender.currentTitle as NSString).floatValue
displayLabel.text = "\(firstNumber)"
}
显示错误:
无法将表达式的类型'()'转换为'NSString'类型
在您的代码发送者中,匿名类型为AnyObject。创建IBAction时,可以选择将Sender的类型更改为触发该操作的控件的实际类型(通常是UIButton)。我建议将发送者的类型更改为正确的类型。
否则您将需要将类型转换为发件人的类型,这有点冒险。
let senderAsButton = sender as UIButton
在发送方运行时崩溃的原因不是UIButton。因此,最好修复IBAction方法签名的定义。
另一个问题是UIButton方法currentTitle返回一个可选的。您必须解开它:
firstNumber = (sender.currentTitle! as NSString).floatValue
请注意,如果sender.currentTitle为nil,该代码将崩溃。这样写会更安全:
if let currentTitle = sender.currentTitle as NSString
{
firstNumber = currentTitle.floatValue
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句