加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 常量’result’推断为type(),这可能是意外的

发布时间:2020-12-14 04:59:28 所属栏目:百科 来源:网络整理
导读:@IBAction func operate(sender: UIButton) { if let operation = sender.currentTitle { if let result = brain.performOperation(operation) { displayValue = result } else { displayValue = 0.0 } }} 我是编码的新手,所以请原谅我的编码格式和其他不一
@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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读