Michael
Michael

Reputation: 1030

How does the '?' unwrap an optional in a case let declaration?

Why does the ? in a? unwrap the value during assigning?

I've only seen similar behavior in optional chaining but a ? on a var should be always be followed by a call, member lookup, or subscript as far as I know.

var x: Int? = 42

if case let a? = x {
    print(a)
}

Upvotes: 2

Views: 196

Answers (1)

fphilipe
fphilipe

Reputation: 10054

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
}

Upvotes: 3

Related Questions