常量'结果'推断为具有type(),这可能是意外的

mn1*_*mn1 9 swift ios8

@IBAction func operate(sender: UIButton) {

     if let operation = sender.currentTitle {
         if let result = brain.performOperation(operation) {

            displayValue   = result
         }
         else {
            displayValue = 0.0
         }

    }
}
Run Code Online (Sandbox Code Playgroud)

我是编码的新手,所以请原谅我的编码格式和其他不一致之处.我一直在试用iOS 8介绍斯坦福大学教授的快速编程,我遇到了修改后的计算器问题.

我得到三个错误.第一个是快速编译警告 - 在

if let result = brain.performOperation(operation)
Run Code Online (Sandbox Code Playgroud)

它说

常量'result'推断为type()可能是意外的.

它给了我这样做的建议----

if let result: () = brain.performOperation(operation)
Run Code Online (Sandbox Code Playgroud)

另外两个错误是

如果让结果行,条件绑定中的绑定值必须是可选类型

无法在"displayValue = result"处将type()的值赋值为Double

如果有人需要有关代码的更多信息,这是github链接.

提前致谢.

cou*_*elk 6

从错误中猜测,我希望它performOperation()应该返回Double?(可选的双倍),而事实上它不返回任何东西.

即它的签名可能是:

func performOperation(operation: String) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

..实际上它应该是:

func performOperation(operation: String) -> Double? {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我认为这样的原因是这一行:if let result = brain.performOperation(operation)调用"展开可选"并且它期望指定的值是可选类型.稍后,将您打开的值分配给似乎为Double类型的变量.

顺便说一句,编写相同的更短(和更可读)的方式是:

displayValue = brain.performOperation(operation) ?? 0.0
Run Code Online (Sandbox Code Playgroud)