Jimmery
Jimmery

Reputation: 10119

Using let in an if statement in Swift

The keyword let is used to define constants in Swift. But I keep finding let being used in if statements, and Ive been wondering why this is, or at least what the advantage to this is.

For example in this code:

if !session.setActive(false, error: &error) {
    println("session.setActive fail")
    if let e = error {
        println(e.localizedDescription)
        return
    }
}

Why is error tested with a let in this statement: if let e = error ?

I understand why error needs testing, so we can make sure we can get at .localizedDesciption but I don't understand why we cant just do something like:

    if error {
        println(error.localizedDescription)

Outside of this example Ive also noticed let being used in a lot of other if statements. What are the advantages to this? I would love to know the thinking behind it.

Finally, can var be used in an if statement in the same way?

Upvotes: 3

Views: 4099

Answers (2)

Marius Schulz
Marius Schulz

Reputation: 16440

The process is called optional binding. You use it to check whether the optional (error in your case) contains a value, and if yes, to assign that value to the bound constant (e in your case).

You may also use var instead of let to bind the value to a variable rather than a constant:

if var error = error {
    // Do something with error
    println(error.localizedDescription)
    return
}

Note that I used the same name (error) in the snippet above. Within the if block, error is no longer of an optional type.

Upvotes: 5

ChikabuZ
ChikabuZ

Reputation: 10185

Also you can use the same name:

 if let error = error {
     println(error.localizedDescription)
     return
 }

Upvotes: 2

Related Questions