常量'结果'推断为具有type(),这可能是意外的 [英] constant 'result' inferred to have type (), which may be unexpected

查看:651
本文介绍了常量'结果'推断为具有type(),这可能是意外的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@IBAction func operate(sender: UIButton) {

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

            displayValue   = result
         }
         else {
            displayValue = 0.0
         }

    }
}

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

I am new to coding so pardon my coding format and other inconsistencies. I have been trying out the iOS 8 intro to swift programming taught by Stanford university and I have ran into a problem with the modified calculator.

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

I get three errors. The first one is a swift compiler warning - at

if let result = brain.performOperation(operation)

它说


常量'结果'推断出类型()可能是意料之外的。

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

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

It gives me the suggestion to do this ----

if let result: () = brain.performOperation(operation)

另外两个错误是


如果让结果行

Bound value in a conditional binding must be of Optional type at if let result line

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

Cannot assign a value of type () to a value of Double at "displayValue = result"

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

Here is the github link if anyone needs more information on the code.

提前致谢。

推荐答案

从错误中猜测,我希望 performOperation()应该返回 Double?(可选的双倍),而事实上它什么也不返回。

Guessing from the errors, I expect that performOperation() is supposed to return Double? (optional double) while if fact it returns nothing.

即它的签名可能是:

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

..实际上它应该是:

.. while in fact it should be:

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

我认为的原因是这一行:如果让结果= brain.performOperation(操作)调用展开可选并且它期望指定的值是可选类型。稍后你将你打开的值分配给似乎是Double类型的变量。

Reason why I think so is that this line: if let result = brain.performOperation(operation) is call "unwrapping the optional" and it expects that the assigned value is an optional type. Later you assign the value that you unwrap to the variable that seems to be of Double type.

顺便说一句,写入相同的更短(也更可读)的方法是:

By the way, the shorter (and more readable) way to write the same is:

displayValue = brain.performOperation(operation) ?? 0.0

这篇关于常量'结果'推断为具有type(),这可能是意外的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆