3

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?

geoff
  • 2,251
  • 1
  • 19
  • 34

2 Answers2

2
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.

Cristik
  • 30,989
  • 25
  • 91
  • 127
1

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 an Optional<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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • "matches the case that UIApplication.shared.delegate is not nil" I think you meant to say it matches the case that the app delegate doesn't even implement the `window` property, since it's an [optional Objective-C property](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623056-window). – TylerP Nov 01 '19 at 21:34
  • 1
    Optional properties in an Objective-c protocol are optionals in Swift (and nil if the property is not implemented) so that is essentially the same. But you are right, thanks for the feedback. – Martin R Nov 01 '19 at 22:11