The if-let
construction is sort of superfluous in a simple case like this, but in a more complicated piece of code it can be useful. You can use it in a lot of the same ways you’d use an assignment in a conditional in (Obj)C (remember if (self = [super init])
).
For example, if the optional being tested is a computed property:
var optionalName: String? {
get {
if checkTouchID() {
return "John Appleseed"
} else {
return nil
}
}
}
var greeting = "Hello!"
if optionalName {
greeting = "Hello, \(optionalName)"
}
Paste that into a playground, along with a stub implementation of checkTouchID()
that returns true
, and you’ll immediately see in the results area that the optionalName
getter is executing twice. If you use an if-let
construction instead, you’ll only execute the getter once.
This also true — and perhaps more commonly useful — if you have a series of chained optional calls, as in the if let johnsStreet = john.residence?.address?.street
example from the docs. You don’t want to rewrite the whole chain in the body of the if
statement, much less recompute it.
7
solved Why use an extra let statement here? [duplicate]