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

空扰寡人 提交于 2019-12-10 02:41:52

问题


@IBAction func operate(sender: UIButton) {

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

            displayValue   = result
         }
         else {
            displayValue = 0.0
         }

    }
}

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.

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

if let result = brain.performOperation(operation)

It says

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

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

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

The other two errors are

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 if anyone needs more information on the code.

Thanks in advance.


回答1:


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

I.e. it's signature is probably:

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

.. while in fact it should be:

func performOperation(operation: String) -> 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



回答2:


It looks like brain.performOperation() does not return a result at all, so there is no optional value, too.



来源:https://stackoverflow.com/questions/31398842/constant-result-inferred-to-have-type-which-may-be-unexpected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!