iosswiftitunesu

Swift error: Initializer for conditional binding must have Optional type, not '()'


I'm doing the course of iTunes University called "Developing iOS 8 Apps with Swift". On the third video I encountered with a problem that did not happen in the video, even though it was the same code, that is as follows:

class ViewController: UIViewController{

…

@IBAction func operate(sender: UIButton) {
        if userIsInTheMiddleOfTypingANumber{
            enter()
        }
        if let operation = sender.currentTitle {
            if let result = brain.performOperation(operation) { > ERROR HERE
                displayValue = result
            } else {
                displayValue = 0
            }
        }
    } 
…
}

After reading many explanations of this error I suppose the problem comes from here:

class CalculatorBrain
{

…
func performOperation(symbol: String) {
        if let operation = knownOps[symbol] {            opStack.append(operation)
        }
    }
}

Thank you if you can help me!


Solution

  • performOperation doesn't return anything and needs to return an optional type so that it can be used in your if let statement (to check if it did indeed return a value) and that's what it could be moaning about.

    Try:

    func performOperation(symbol: String) -> Int? {
    

    which means it could return an Int, and then your if let statement should be happy.