@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.
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
It looks like brain.performOperation()
does not return a result at all,
so there is no optional value, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With