Reputation: 2276
I am reviewing some pull requests internally, and see a pattern matching statement like this:
if case let presentationAnchor?? = UIApplication.shared.delegate?.window,
Now I understand ??
is a nil coalescing operator when used on the other side of the =
, e.g. aString ?? "default value"
, but what is it when it's used on the left hand side of the =
assignment? Is it some way to unwrap an optional when assigning it?
Upvotes: 3
Views: 148
Reputation: 539735
In the context of pattern matching, x?
is the “optional pattern” and equivalent to .some(x)
. Consequently, case x??
is a “double optional pattern” and equivalent to .some(.some(x))
.
It is used here because UIApplication.shared.delegate?.window
evaluates to a “double optional” UIWindow??
, compare Why is main window of type double optional?.
Therefore
if case let presentationAnchor?? = UIApplication.shared.delegate?.window
matches the case that UIApplication.shared.delegate
is not nil and the delegate implements the (optional) window
property. In that case presentationAnchor
is bound to the “doubly unwrapped” UIWindow
.
See also Optional Pattern in the Swift reference:
An optional pattern matches values wrapped in a
some(Wrapped)
case of anOptional<Wrapped>
enumeration. Optional patterns consist of an identifier pattern followed immediately by a question mark and appear in the same places as enumeration case patterns.
Upvotes: 1
Reputation: 32786
if case let someVar? = anotherVar
is sugar syntax for
if case let .some(someVar) = anotherVar
Adding another question mark expands to a double optional, equivalent to
if case let .some(.some(someVar)) = anotherVar
Two question marks on the left side of the pattern match means the if
will be executed if the double optional holds a non-nil value at both levels.
Upvotes: 2