One thought, this pattern matching syntax probably implies that the shorthand (omitting the RHS) is supported for any enum rather than just optionals (and for forms other than just foo?
).
For example, if this is allowed for optionals:
let foo: String?
if case let foo? { .... }
// as shorthand for
if case let foo? = foo { .... }
then what about other types of pattern matching / value unwrapping, like using .some
instead of ?
:
let foo: String?
if case .some(let foo) { .... }
// as shorthand for
if case .some(let foo) = foo { .... }
or unwrapping the value of a Result
:
let result: Result<String, Error>
if case .success(let result) { .... }
// as shorthand for
if case .success(let result) = result { .... }
I'm not sure if we would want to generalize this shorthand syntax to support all enums (there's probably not a good way to support enum cases with multiple associated values here), On the other hand, special-casing it to only support optionals seems somewhat undesirable. We don't have this generality problem for if let foo = foo
, since it's a special construct specifically for optionals.
Another reason I think we should be sugaring if let foo = foo
optional binding syntax instead of pattern matching, is that optional binding is a foundational / beginner-level feature whereas pattern matching (especially if case
) is somewhat more advanced.
For example, in The Swift Programming Language guide, optional binding syntax is covered in "The Basics" immediately after introducing optionals. On the other hand, pattern matching syntax is not covered until much later, in the section on enum associated values. That discussion also only covers switch
statements -- I don't see any discussion about if case
syntax.
In my personal experience, folks tend to find optional binding syntax far more intuitive than pattern matching (which is notoriously difficult to learn / remember / master).