TL DR
Syntactic sugar _? can be used in pattern matching as a replacement for .some(_) ( .some ).
- Where in the official language are documents documented?
Background
Sometimes I use syntactic sugar _? for a pattern matching an optional value with a specific value ( .some ) where I don't need to use the actual wrapped value, just the fact that it is not nil . Thoughtful examples:
let foo: Int? = 1 switch foo { case _?: print("Non-nil, but I have no need for the wrapped value here!") /* as compared to case .some: ... or case .some(_): ... */ default: print("Nil") } let arr = [1, nil, 3, 4, nil, 6] var numberOfNonNil = 0 for case _? in arr { numberOfNonNil += 1 } print(numberOfNonNil) // 4
I realized that I did not know where this functionality is documented in the official language, and since I look back even for a specific purpose, I could not find any explicit mention of this.
Research my own
The wildcard _ well documented in the Language Reference - Patterns and contains, in particular, the following (possibly) relevant grammar:
GRAMMATIC IMAGE
pattern → template-template-annotation (option)
...
The wildcard matches and ignores any value and consists of an underscore ( _ ). Use a wildcard pattern when you don't care about matching values.
Postfix ? documented in Reference Reference - Types - Optional , but I'm not sure if this is an important part for _? connection _? sugar:
Swift language defines postfix ? as syntactic sugar for named type Optional<Wrapped> , which is defined in the Swift library standard. In other words, the following two declarations are: equivalent:
var optionalInteger: Int? var optionalInteger: Optional<Int>
In both cases, the optionalInteger variable is declared as having an optional integer type. Note that spaces cannot appear between type and ? .
I'm a little vague if the last link is here, and I don't see any of the links above, directly explaining how syntax sugar is _? in the context of pattern matching, it is equivalent to .some(_) (where in the latter case the pattern may be omitted, .some ).
Question
- Where in the official language documents is syntactic sugar
_? documented? (I just do not understand the existing documentation for this function, for example, in terms of grammar?)