Loading...

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")
    fallthrough
case 2:
    print("It's one or two")
default:
    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.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on October 22, 2023
Image placeholder

Keep reading

If this article was helpful, others might be too

question swift macos September 15, 2024 How to open macOS System Settings (or a specific pane) programmatically with Swift?

To programmatically open a specific pane in System Settings (formerly System Preferences) like “Privacy & Security > Camera” on macOS using SwiftUI, you can leverage the NSWorkspace class to open specific preference panes using URL schemes.

question swiftui swift September 8, 2024 How to loop through an enum in SwiftUI?

In SwiftUI, looping through an enum is not directly possible without some extra work because enums in Swift don’t inherently support iteration. However, you can achieve this by making the enum CaseIterable, which automatically provides a collection of all cases in the enum.

question swiftui swift October 7, 2024 How to zoom in and zoom out a SwiftUI view?

In a macOS or iOS app, you can easily add a zoom feature to any SwiftUI view with the scaleEffect modifier. In the below example, I am using a Slider to control the zoom level. Here’s how you can implement zooming in and out with a slider: