Swift – Switch cases
Firstly, in Swift, you no longer need to add break statement like other conventional programming languages like C. The other use of break was that if you don’t call break, it will automatically execute other cases too. For this purpose, we have fallthrough method that makes the next cases to be executed even if the current case succeeds. Let us now look at some examples.
Simple Switch case example
let a = 10 switch (a){ case 1: println("Hello") case 10: println("World") default: println("Nothing") }
Output
World
Another important thing to note is that, cases should be exhaustive and hence we should add a default case to make it exhaustive. The default case should have at least one statement. The one statement could be even break if you don’t need to do any other stuff.
Switch Ranges example
let a = 4 switch (a){ case 1...10: println("Hello") default: break }
Output
Hello
In the above example refers to range 1 to 10 with both 1 and 10 included.
Switch with fallthrough example
let a = 4 switch (a){ case 1...10: println("One to ten") fallthrough case 5...10: println("five to ten") default: break }
Output
One to ten five to ten
As you can see in the above example, fallthrough enable all the subsequent cases to be executed. You may need to use break in case you want to break in one of the cases while using fallthrough.
Simple tuples example
let a = ("raj", 10) switch (a){ case ("raj",10): println("Raj") case ("john",20): println("John") default: break }
Output
Raj
Tuples enables us to pass multiple values and it is supported in switch case as well. In the above example, we have used a simple string and number comparison.