constant 'result' inferred to have type ()

2019-04-21 10:18发布

@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.

标签: swift ios8
2条回答
等我变得足够好
2楼-- · 2019-04-21 10:44

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
查看更多
手持菜刀,她持情操
3楼-- · 2019-04-21 10:58

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

查看更多
登录 后发表回答