Swift Pattern Matching in Detail
Benedikt Terhechte (via Chris Lattner):
The main feature of
switchis of course pattern matching, the ability to destructure values and match different switch cases based on correct match of the values to the cases.[…]
So, how do you best implement this new restriction? You could just have an
if/elseswitch for buy and for sell, but that would lead to nested code which quickly lacks clarity - and who knows maybe these Wall Street guys come up with further complications. So you define it instead as additional requirements on the pattern matches[…][…]
By default, and unlike C/C++/Objective-C,
switchcasesdo not fall through into the next case which is why in Swift, you don’t need to writebreakfor every case. You can opt into traditional fallthrough behaviour with thefallthroughkeyword.[…]
The
casekeyword can be used in for loops just like inswitchcases.
case can also be used with guard, although only wildcard and identifier patterns work with for and guard.