Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 409
Harry Avatar asked Aug 20 '15 16:08

Harry


3 Answers

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 {
...
}
like image 51
LorenzSchaef Avatar answered Nov 18 '22 18:11

LorenzSchaef


Writing

if let score1 {

doesn't make sense. If you want to see if score has a value, use

if score1 != nil {

or

if let score = score1 {

The last case binds a new non-optional constant score to score1. This lets you use score inside the if statement.

like image 41
Aderstedt Avatar answered Nov 18 '22 19:11

Aderstedt


The code in your question is similar to something I saw in the swift book and documentation and they are correct.

Your playground is just using an old version of swift which currently doesn't support this syntax. Using a beta version of XCode should fix

https://www.reddit.com/r/swift/comments/vy7jhx/unwrapping_optionals/

like image 1
Robin Avatar answered Nov 18 '22 19:11

Robin