This is syntactic sugar for option patterns. The docs on option pattern says:
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.
Thus, your code is the same as:
var x: Int? = 42
if case .some(let a) = x {
print(a)
}
It's not typical for simple if
statements as you can just do this instead:
if let a = x {
print(a)
}
But consider an enum wrapped in an optional:
enum Foo {
case bar
case baz
}
let y: Foo? = .bar
switch y {
case .none: break
case .some(.bar): break
case .some(.baz): break
}
This switch can be written in a more succinct way using some sugar:
switch y {
case nil: break
case .bar?: break
case .baz?: break
}