TSPL states that
If any of the values in the optional bindings are
nil
or any Boolean condition evaluates tofalse
, the wholeif
statement’s condition is considered to befalse
.
So I'm surprised to find that optional binding checks for only one level of optionality:
let x: [Int?]: [nil, 1, 2]
if let y = x.first {
print(type(of: y)) // prints "Optional<Int>"
print(y) // prints "nil"
}
In many cases in the language (e.g. optional chaining (thanks to @cukr for the correction) conditional type casting try?
), multi-level optionality is flattened to just one level (e.g. Optional<Optional<Optional<_>>>
is treated as Optional<_>
). So I wonder what the rationale behind the different behavior for optional binding is, or if either this behavior or the documentation is incorrect?