I'm reading Apple's developer documentation on Optional Binding
Why can't I use:
if someOptional? {
statements
}
Instead of
if let constantName = someOptional {
statements
}
Why when there is no need for a local variable or constant?
I'm reading Apple's developer documentation on Optional Binding
Why can't I use:
if someOptional? {
statements
}
Instead of
if let constantName = someOptional {
statements
}
Why when there is no need for a local variable or constant?
Why can't I use: if someOptional? {...}
Because the ?
suffix on an optional variable is reserved for optional chaining, which allows you to access a property or call a method on a given optional variable. For example:
// returns an optional version of a given property
let aProperty = anOptional?.someProperty
// calls the method if aProperty contains a value – otherwise doesn't
aProperty?.doSomething()
If you just want to check whether an optional contains a value, but don't care about that underlying value, you can simply compare it with nil
. For example:
if anOptional != nil {
// do something
}
The simple answer is that someOptional is an Optional, whereas constantName is a Type.
An Optional is not simply the state of a variable, it's an entirely different type. If you were to set var someOptional: String?
to var someOptional: String
, you're not unwrapping someOptional, you're actually changing the type of someOptional.
It's functionally the same as changing var someOptional: String
to var someOptional: Int