Control flow
Some of Swift's control flow and control transfer statements are either considerably more flexible than their counterparts in other languages, or behave a little differently to what one may be accustomed to.
Using switch
We saw in Chapter2, Basic Swift that a Swift switch
statement will test for the equality of any type, not just Int
, and that we can test for values within a range.
That's just the start. The switch
statement is an extremely flexible mechanism, and is capable of reducing large amount of if else
code to much more concise, readable, and elegant blocks of code.
Compound cases
Cases can be combined on one line, if they are required to share the same block of code:
let a = 1 switch a { case 1,3,5,7,9: print("a is a single digit positive odd number") case 0, 2,4,6,8: print("a is a single digit positive even number") default: print("a is not a single digit positive number") }
Tuple matching
If we are dealing with tuples in a switch
statement, we can test against...