Harry
Harry

Reputation: 291

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()

Upvotes: 21

Views: 40833

Answers (5)

Saneesh Antony
Saneesh Antony

Reputation: 1

You can unwrap it using this:

import Cocoa

class Person {
    var score1: Int? = 9

    func sum() {
        print("\(score1 != nil ? "YES" : "NO")")
    }
 }

And then call it like:

 var objperson = Person()
 objperson.sum()

Upvotes: -1

Robin
Robin

Reputation: 1365

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/

Upvotes: 3

Aderstedt
Aderstedt

Reputation: 6518

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.

Upvotes: 6

LorenzSchaef
LorenzSchaef

Reputation: 1543

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 {
...
}

Upvotes: 19

Cole
Cole

Reputation: 2646

the problem is that if let assumes you want to create a constant score1 with some value. If you just want to check if it contains a value, as in not nil you should just do it like below:

if score1! != nil {
     // println("yes")

So your full code would look like this:

class Person {
    var score1: Int? = 9

    func sum() {
        if score1 != nil {
            println("yes")
        }
        else {
            println("no")
        }
    }
}

var objperson = Person()
objperson.sum()

Upvotes: 0

Related Questions