Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Fallthrough in Switch Statement
Written by Team Kodeco

In a switch statement, each case is executed independently of the others, meaning that the execution of the code stops after the code for a matching case is executed. The fallthrough keyword allows you to continue execution to the next case, even if the current case is matched. Here’s an example of using fallthrough to execute multiple cases:

let number = 3
switch number {
case 1:
  print("one")
case 2:
  print("two")
case 3:
  print("three")
  fallthrough
case 4:
  print("four")
default:
  print("other")
}
// Output: three four

In this example, the variable number is set to 3. When the switch statement is executed, the code for the case 3 is executed and the fallthrough keyword is encountered, so the code for the next case, case 4 is executed.

© 2024 Kodeco Inc.