常量 'result' 被推断为 () 类型,这可能是意想不到的

constant 'result' inferred to have type (), which may be unexpected

@IBAction func operate(sender: UIButton) {
   
     if let operation = sender.currentTitle {
         if let result = brain.performOperation(operation) {
    
            displayValue   = result
         }
         else {
            displayValue = 0.0
         }
    
    }
}

我是编码新手,请原谅我的编码格式和其他不一致之处。我一直在尝试 iOS 8 intro to swift programming 由斯坦福大学教授,我 运行 遇到了修改后的计算器的问题。

我得到三个错误。第一个是 swift 编译器警告 - 在

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 如果有人需要有关代码的更多信息。

提前致谢。

看起来 brain.performOperation() 根本不是 return 结果, 所以也没有可选值。

从错误中猜测,我预计 performOperation() 应该是 return Double?(可选的双精度),而如果事实上它 return 什么都没有。

即它的签名可能是:

func performOperation(operation: String) {
    // ...
}

.. 而实际上应该是:

func performOperation(operation: String) -> Double? {
    // ...
}

我这么认为的原因是这一行:if let result = brain.performOperation(operation) 是调用 "unwrapping the optional" 并且它期望分配的值是可选类型。稍后您将解包的值分配给似乎是 Double 类型的变量。

顺便说一句,更短(更易读)的写法是:

displayValue = brain.performOperation(operation) ?? 0.0