Friday, August 21, 2015

Swift Pattern Matching in Detail

Benedikt Terhechte (via Chris Lattner):

The main feature of switch is 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 / else switch 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, switch cases do not fall through into the next case which is why in Swift, you don’t need to write break for every case. You can opt into traditional fallthrough behaviour with the fallthrough keyword.


The case keyword can be used in for loops just like in switch cases.

case can also be used with guard, although only wildcard and identifier patterns work with for and guard.

Comments RSS · Twitter

Leave a Comment