How to Write a Switch statement in Swift?

Switch in Swift

Tested on: Xcode 12.2, Swift 5.3

Switch is an alternative to if statement for executing code with different conditions.

  1. Switch Statement
  2. Compound Cases
  3. Where





1. Switch

A switch statement contains the following keywords switch, case, and default. Look at the code below:

Swift Code :

let number = 6 % 2

switch number {
case 0:
   print("Even Number")
default:
   print("Odd Number")
}

Output :

Even Number

The purpose of the code above is to determine whether or not a number is zero. First, theSwitchtakes in a value which is a number. Then, the value is checked in the case. If it is equal to zero in this example, it will print out Even Number. Else, it will print out Odd Number.

Mutiple Cases

You can also have mutiple cases in a Switch. However, you can only have one default or no default (If you are using enum).

Swift Code :

let food = "ice cream"

switch food {
case "ice cream" :
   print("I Love it!")
case "pizza" :
   print("Emm Yummy!")
case "bread" :
   print("Should I have more?")
default:
   print("What is this?")
}

Output :

I Love it!

Range

You can use range as a value in case.

Swift Code :

let postiveNumber = 190

switch postiveNumber {
case 0...99:
   print("Less than 100")
default:
   print("More than 100")
}

Output :

More than 100




2. Compound Cases

In the above example, there is only one value in a case but you can also have more than one value in a case. This allows you to make you code cleaner without mutiple cases to execute the same code!

Swift Code :

let food = "ice cream"

switch food {
case "ice cream", "bingsu", "rice cake", "chicken rice":
   print("I Love it!")
case "pizza", "Hokkien prawn mee" :
   print("Emm Yummy!")
case "bread", "Fajitas", "Salad" :
   print("Should I have more?")
default:
   print("What is this?")
}

Output :

I Love it!




3. Where

Switch allows you to use a where caluse to check for additional conditions.

Swift Code :

let number = 6

switch number {
case let even where even % 2 == 0:
   print("Even Number")
default:
   print("Odd Number")
}

Output :

Even Number