Search code examples
swifttypesoption-typeinitializer

Error message: initialiser for conditional binding must have optional type, not '()'


I am getting error:

initialiser for conditional binding must have optional type, not '()'.

Using Swift language, below is the code:

if let result = brain.performOperation(operation)

Solution

  • I think I can answer your question, but I don't know how much it will help you.

    The way if let someVar = someOptional { } is used is to check the value of a variable (someOptional) to see if it is nil or a "value". If it is not nil then someVar will be assigned the non-nil value of someOptional and execute the code between { } which can safely reference someVar, knowing it is not nil. If someOptional is nil then the code within { } is bypassed and not executed.

    The comment you posted above indicates that the performOperation() method is this:

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

    This method does not return anything, or more formally it returns void aka (). void, or () is not a value, nor is it nil.

    So when you have this statement

    if let result = brain.performOperation(operation) { }

    the compiler complains because it expects brain.performOperation(operation) to return either nil or a value, but not void aka () which is exactly what the method returns.

    If you are still confused about optionals, be sure to read as much as you can of the Swift Language Reference. Optionals are a big part of the language and once you get used to them you will find them very invaluable.