How to not break automatically in switch statements in Swift?

question swift
Ram Patra Published on October 22, 2023

In Swift, the switch statement doesn’t automatically fall through to the next case. Each case block is designed to execute only the code within that case, and it doesn’t continue to the next case unless you use the fallthrough keyword.

If you don’t want Swift to break automatically after each case and you want to intentionally allow fall-through behavior, you can use the fallthrough statement to explicitly specify this behavior. Here’s an example:

let number = 1

switch number {
case 1:
    print("It's one")
case 2:
    print("It's one or two")
    print("It's something else")

In this code, when number is 1, it will print both “It’s one” and “It’s one or two” because of the fallthrough statement.

If you don’t include fallthrough, Swift will execute only the code in the matching case and then exit the switch statement. So, by default, Swift breaks after each case, and you need to explicitly use fallthrough if you want to allow fall-through behavior. This is different to, let’s say, Java where you have to explicitly use break if you want to only execute code in the matching case.

Ram Patra Published on October 22, 2023
Image placeholder

Keep reading

If this article was helpful, others might be too

question swift November 17, 2023 How to loop through an array of structs in Swift?

Looping through an array of structs in Swift is straightforward and can be done in several ways depending on what you need to achieve. Here’s how to do it:

question swift November 17, 2023 Different ways to compare strings in Swift

Comparing two strings in Swift is straightforward and can be done using the equality operator ==. This operator checks if two strings are exactly the same in terms of their characters and the order in which these characters appear.

question swift November 16, 2023 How to check whether a value is not nil in Swift and assign it to a variable at the same time?

In Swift, there are several ways to check for nil and assign a value to a variable, depending on the context and what you want to achieve. Here are some common approaches: