A constant "result" that has type (), which may be unexpected

@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 I apologize for my coding format and other inconsistencies. I tried the introduction of iOS 8 to the fast programming taught by Stanford University, and I had a problem with a modified calculator.

I get three errors. The first is a quick compiler warning - in

 if let result = brain.performOperation(operation) 

It says

the constant 'result' deduces that it has type (), which may be unexpected.

It gives me a suggestion to do it ----

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

Other two errors:

The bound value in the conditional binding must be optional if the result string

Unable to assign type () value to Double value on "displayValue = result"

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

Thanks in advance.

+5
source share
2 answers

Guessing the errors, I expect that performOperation() should return a Double? (optional double), and if the fact returns nothing.

those. this is probably the signature:

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

.. while in reality it should be:

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

The reason why I think so is because this line: if let result = brain.performOperation(operation) is a call to "expand optional", and it expects the assigned value to be an optional type. Later, you assign a value that you expand into a variable that appears to be of type Double.

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

 displayValue = brain.performOperation(operation) ?? 0.0 
+2
source

It appears that brain.performOperation() does not return a result at all, so there is no extra value.

+1
source

All Articles