0

While reading the official Apple Guide I found this

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello \(name)"
}

There is a constant declaration and assignment where I — as a beginner — expected an expression returning a boolean. But the condition of this if statement seems to get true as the value, because the code inside the parentheses is being executed.

Does the initialization of a constant return a boolean value or something that a if statement can use as a condition?

0

1 Answer 1

0

This is called Optional Binding. Quoting from the Basics -> Optionals -> Optional Binding section of the Swift Language Guide.

You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action.

What this if let construct is doing is checking if someOptional is exists. If it isn't nil/.None then it "binds" the Optional value to a constant.

if let constantName = someOptional {
    ...
}

This can be thought of as:

if someOptional != nil {
    let constantName = someOptional!
    ....
 }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.