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?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Tobias
  • 13
  • 2

1 Answers1

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!
    ....
 }
Kevin
  • 16,696
  • 7
  • 51
  • 68