@IBAction func operate(sender: UIButton) { if let operation = sender.currentTitle { if let result = brain.performOperation(operation) { displayValue = result } else { displayValue = 0.0 } } }
我是编码的新手,所以请原谅我的编码格式和其他不一致之处.我一直在试用iOS 8介绍斯坦福大学教授的快速编程,我遇到了修改后的计算器问题.
if let result = brain.performOperation(operation)
它说
constant ‘result’ inferred to have type () which may be unexpected.
它给了我这样做的建议—-
if let result: () = brain.performOperation(operation)
另外两个错误是
Bound value in a conditional binding must be of Optional type at if let result line
Cannot assign a value of type () to a value of Double at “displayValue = result”
Here is the github link如果有人需要有关代码的更多信息.
提前致谢.
解决方法
从错误中猜测,我希望performOperation()应该返回Double? (可选双),如果事实它什么都不返回.
即它的签名可能是:
func performOperation(operation: String) { // ... }
..实际上它应该是:
func performOperation(operation: String) -> Double? { // ... }
我认为这样的原因是这一行:如果让result = brain.performOperation(operation)调用“展开可选”并且它期望指定的值是可选类型.稍后,将您打开的值分配给似乎为Double类型的变量.
顺便说一句,编写相同的更短(和更可读)的方式是:
displayValue = brain.performOperation(operation) ?? 0.0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。