3

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?

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Suggested reading: optional binding
I think OP's issue is that we already have a perfectly good variable (error), so why rebind it as e...
Indeed, why do if let e=error when we could do if error! ? What makes let e=error safer than error! when tested inside an if statement?
@Jimmery If you do error! and the optional doesn't have a value, a runtime error will occur. That's exactly what we're trying to avoid.
2

Also you can use the same name:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.