Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

ios8

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

like image 236
mn1 Avatar asked Jul 14 '15 06:07

mn1


2 Answers

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
like image 52
0x416e746f6e Avatar answered Nov 18 '22 10:11

0x416e746f6e


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

like image 44
vadian Avatar answered Nov 18 '22 10:11

vadian