9. Switch Statement in Swift

Switch statement is more convenient and good alternative of if statement. If you have different conditions, you can use multiple if statements. if-else or nested if can make the code lengthy and hard to manage. Developer always try to make the code clean and manageable. Switch statement is a very good alternative.

First look at the syntax:

	case value:
		your code here

statement takes a variable and compares with available cases which you have mentioned in the block.

	case value1:
		your code here

	case value2:
		your code here

        default :
	        Your code here


You can also add default block as well.  Default block will execute when all cases will be failed.

Swift is a very modern language it handles lots of thing by itself. As compare to other languages you do not need to add break statement in switch. Although you could add break with each case but its not necessary.

var superhero = "SpiderMan"
switch superhero{
    case "CaptainAmerica":
        println("Hey i am C A...")
    case "SpiderMan":
        println("Hello internet....I have my own web")
    case "ThunderCats":
        println("Thunder thunder thunder cats.....")

        println("Super heroes are sleeping.... help your-self")

Swift and Safety

Swift is also very concern with safety, it handles lots of errors by itself. Its very common that developers forget to write “default” when they are working with switch statement. In this previous example, just remove

        println("Super heroes are sleeping.... help your-self")

suddenly you will see error: switch must be exhaustive, consider adding a default clause.


Combine Cases

In previous example you can see that each case has its own code block but sometime different values require same code to be executed. Swift provides this functionality in switch. You can add more than one value in one case. See very simple example

var value = 8

switch value{
    case 2,4,6,8 :
    case 1,3,5,7,9:
        println("All numbers after 9")


Range based switch

As you have seen in Loops that Swift provides range based loop, developer can start and end loop at any point

for i in 5...20 {
    println("Rang Based Loop \(i)")

This functionality is also available in Switch. Check this example

var windspeed = 20

switch windspeed{
    case 1...9:
        println("Nice weather lets play basket ball")
    case 10...19:
        println("WOW ... Lets Surfing ")
    case 20...30:
        println("Better Stay at home")
        println("Weather Tower is not working")



Download file from GitHub