Menu
Coddy logo textTech

Switch Statement

Part of the Fundamentals section of Coddy's Swift journey — lesson 29 of 86.

When you're checking a single value against many possible matches, the switch statement offers a cleaner alternative to long chains of else if. It's especially useful when you have multiple distinct cases to handle.

let day = "Monday"

switch day {
case "Monday":
    print("Start of the week")
case "Friday":
    print("Almost weekend!")
case "Saturday", "Sunday":
    print("Weekend!")
default:
    print("Regular day")
}

Swift compares the value after switch against each case. When it finds a match, it executes that case's code. Notice how you can combine multiple values in a single case using commas.

The default case handles any values that don't match the other cases — it's required when your cases don't cover every possible value. Unlike some other languages, Swift's switch doesn't fall through to the next case automatically, so you don't need break statements.

let grade = "B"

switch grade {
case "A":
    print("Excellent")
case "B":
    print("Good")
case "C":
    print("Fair")
default:
    print("Needs improvement")
}
challenge icon

Challenge

Easy
Write a function getSeasonActivity that takes season and returns a recommended activity for that season.

Use a switch statement to match the season and return the appropriate activity.

Cases:

  • "Spring" - return "Go hiking"
  • "Summer" - return "Go swimming"
  • "Fall", "Autumn" - return "Go apple picking" (both should return the same activity)
  • "Winter" - return "Go skiing"
  • Any other value - return "Stay home"

Parameters:

  • season (String): The name of the season

Returns: The recommended activity as a String

Cheat sheet

The switch statement provides a cleaner alternative to multiple else if statements when checking a single value against many possible matches.

Basic syntax:

let day = "Monday"

switch day {
case "Monday":
    print("Start of the week")
case "Friday":
    print("Almost weekend!")
case "Saturday", "Sunday":
    print("Weekend!")
default:
    print("Regular day")
}

Key points:

  • Swift compares the value after switch against each case
  • Multiple values can be combined in a single case using commas
  • The default case handles values that don't match other cases and is required when cases don't cover every possible value
  • Swift's switch doesn't fall through automatically, so break statements are not needed

Example with return values:

let grade = "B"

switch grade {
case "A":
    print("Excellent")
case "B":
    print("Good")
case "C":
    print("Fair")
default:
    print("Needs improvement")
}

Try it yourself

func getSeasonActivity(season: String) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals