Why can I use a non-optionals assignment in an Optional Pattern?

The problem I am trying to solve is that I can't stack let statements in a guard statement if in the middle I need to set a non-optional value (think parsing some huge JSON object):


guard
  let foo = dict[someKey] as? [String: Any],
  let moo = foo[anotherKey] as? [String],
  moo.count > 2,
  case let whatIwant = moo[1],
  ...


I was actually given this technique years ago in Swift 2 or something, on this forum!


So I'm using it now in Swift 4.1, and started wondering - why is this possible? I looked at the Swift Programming Language, and all I can find is something on "Optional Patterns", but the examples and discussion really don't fit.


Why does this work?

Accepted Reply

You can think of an if/guard case pattern as kinda equivalent to a switch statement:


switch moo [1]
{
case let whatIwant:
  …
}


Note that the "= moo[1]" part is just the syntax for specifying the value to "switch" on (i.e. to pattern-match against).


This particular case pattern in a "switch", if you leave out the binding, is the same as:


case _:


which in turn is the same as:


default:


So, what your pattern match does is to match any value, and to bind that value to your "whatIwant" variable. It's really, really difficult to read, but it makes sense if you can get your mind wrapped around it. 🙂

Replies

You can think of an if/guard case pattern as kinda equivalent to a switch statement:


switch moo [1]
{
case let whatIwant:
  …
}


Note that the "= moo[1]" part is just the syntax for specifying the value to "switch" on (i.e. to pattern-match against).


This particular case pattern in a "switch", if you leave out the binding, is the same as:


case _:


which in turn is the same as:


default:


So, what your pattern match does is to match any value, and to bind that value to your "whatIwant" variable. It's really, really difficult to read, but it makes sense if you can get your mind wrapped around it. 🙂

I tracked down my orignal question - OOper answered it: https://forums.developer.apple.com/thread/13477