Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Switch Statements in Swift
Written by Team Kodeco

A switch statement in Swift is used to execute different pieces of code depending on the value of a given expression. It’s a powerful tool for controlling the flow of your program and can be used to replace complex if-else statements.

Here is an example of a simple switch statement:

let grade = "A"

switch grade {
case "A":
   print("Excellent work!")
case "B":
  print("Good job!")
case "C":
  print("Average work.")
default:
  print("Work needs improvement.")
}
// Output: Excellent work!

In this example, the grade variable is being checked against several cases and it prints an appropriate message for each case.

Use Ranges in a Switch Statement

It’s also possible to use ranges in the switch case statement like this:

let number = 5

switch number {
case 1...10:
  print("Number is between 1 and 10.")
case 11...20:
  print("Number is between 11 and 20.")
default:
  print("Number is out of range.")
}
// Output: Number is between 1 and 10.

Using Tuples in a Switch Statement

You can also use Tuples in the switch case statement like this:

let point = (1,1)

switch point {
case (0,0):
  print("Point is at the origin.")
case (_,0):
  print("Point is on the x-axis.")
case (0,_):
  print("Point is on the y-axis.")
case (-2...2,-2...2):
  print("Point is within the range of -2 to 2 for both the x and y coordinates.")
default:
  print("Point is outside the defined range.")
}
// Output: Point is within the range of -2 to 2 for both the x and y coordinates.
© 2024 Kodeco Inc.