Swift Tutorials: Understanding `fallthrough` in `switch`

beginner
10 min

Swift Tutorials: Understanding fallthrough in switch

Welcome to our deep dive into the world of Swift programming! Today, we're going to learn about a powerful feature called fallthrough in the switch statement. This concept is essential for controlling the flow of your code and making your programs more efficient. Let's get started! 🎯

The Basics of switch

Before we delve into fallthrough, let's quickly review the switch statement. It's a control structure used to compare a value with multiple constants or cases.

swift
let number = 3 switch number { case 1: print("One") case 2: print("Two") case 3: print("Three") default: print("Not a valid number.") }

In this example, we have a variable number set to 3. We're using switch to compare number with each case. When a match is found, the corresponding code block is executed.

Introducing fallthrough

Now, let's bring fallthrough into the picture. The fallthrough keyword allows a case to execute the code for the next case as well. This can be particularly useful when you want to build upon the results of a previous case.

swift
let number = 3 switch number { case 1: print("One") fallthrough case 2, 3: print("Next number") case 4: print("Four") default: print("Not a valid number.") }

In this example, when number is 1, it prints "One" and then, due to fallthrough, it also prints "Next number". This happens because fallthrough causes the code execution to move to the next case even though the value doesn't match.

Practical Application of fallthrough

Let's make our switch statement more practical by creating a function that calculates the day of the week from a given day number.

swift
func dayOfWeek(day: Int) -> String { switch day { case 1: print("Monday") fallthrough case 2: print("Tuesday") fallthrough case 3: print("Wednesday") fallthrough case 4: print("Thursday") fallthrough case 5: print("Friday") fallthrough case 6: print("Saturday") fallthrough case 7: print("Sunday") fallthrough default: print("Invalid day number.") } return "The day of the week is \(String(describing: day))" } dayOfWeek(day: 3) // Prints "WednesdayThe day of the week is 3"

In this example, we've created a function dayOfWeek that accepts an integer day. Using fallthrough, we print the day of the week for the given day number. Notice that we're not only printing the day of the week but also returning it as a string. This allows us to use the function in other parts of our code.

Quiz Time 📝

Quick Quiz
Question 1 of 1

What does the `fallthrough` keyword do in Swift?

That's all for today! We hope you've enjoyed learning about fallthrough in Swift. Stay tuned for more exciting tutorials on CodeYourCraft! 💡


If you found this tutorial helpful, consider checking out our other Swift tutorials. Remember, practice makes perfect! Happy coding! 🤖