Search code examples
swiftoption-type

Swift Optionals - Variable binding in a condition requires an initializer


I am new to Swift and trying to figure out the Optional concept. I have a small piece of code in Playground which is giving me "Variable binding in a condition requires an initializer" error. Can someone please explain why and how do I fix it?

I only want to print "Yes" or "No" depending on if "score1" has a value or not. Here is the code:

import Cocoa

class Person {
    var score1: Int? = 9

    func sum() {
        if let score1 {
            print("yes")
        } else {
            print("No")
        }
    }//end sum
 }// end person

 var objperson = person()
 objperson.sum()

Solution

  • The if let statement takes an optional variable. If it is nil, the else block or nothing is executed. If it has a value, the value is assigned to a different variable as a non-optional type.

    So, the following code would output the value of score1 or "No" if there is none:

    if let score1Unwrapped = score1
    {
        print(score1Unwrapped)
    
    }
    
    else
    {
        print("No")
    }
    

    A shorter version of the same would be:

    print(score1 ?? "No")
    

    In your case, where you don't actually use the value stored in the optional variable, you can also check if the value is nil:

    if score1 != nil {
    ...
    }