2

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)
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
Michael
  • 1,030
  • 14
  • 29
  • Please read [Optional Pattern](https://docs.swift.org/swift-book/ReferenceManual/Patterns.html#ID520) in [Swift Language Reference](https://docs.swift.org/swift-book/ReferenceManual/AboutTheLanguageReference.html) – vadian Apr 27 '19 at 10:47
  • Related: https://stackoverflow.com/questions/37738614/what-does-case-mean-without-switch-statement-in-swift, https://stackoverflow.com/questions/31453826/swift-optional-patterns – Martin R Apr 27 '19 at 11:07

1 Answers1

3

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
}
fphilipe
  • 9,739
  • 1
  • 40
  • 52