Switch Statement in Swift

The switch statement in Swift is used to execute a particular block of code based on multiple conditions. A switch statement is useful for more than one condition. For one or two conditions, if-else is a better option but for conditions more than that, a switch statement is a better option.

This post was originally posted at https://agrawalsuneet.github.io/blogs/switch-statement-in-swift/ and reposted on Medium on 12th April 2022.

We will try to understand the flow of switch statement in detail but let’s try to understand its basic syntax first.

The switch statement begins with a switch keyword followed by an expression based on which the cases will be evaluated.
The expression is followed by different cases and the code block for each case.
If none of the cases matches, the default block will be executed.
The basic syntax will look like below.

switch (expression)  {
case value1:
// statements
case value2:
// statements

// statements

Let’s try to understand it with a flow chart before taking an example.
The below flow chart explains the basic flow of a switch statement which starts with an expression followed by cases. If the condition matches, the code block for that case will be executed. If non of the cases match, the default case will be executed.

Now let’s see an example for the switch statement.

let dayOfWeek = 2switch dayOfWeek {	    
case 1:

case 2:

case 3:

case 4:

case 5:

case 6:
case 7:

print("Invalid day")
//this will print

Things to notice here

Please continue reading at https://agrawalsuneet.github.io/blogs/switch-statement-in-swift/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.





Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The *Right* Unit Tests for iOS

An intricate, well crafted pocket watch

iPhone back tap for the deaf-blind

Let’s create an app, quickly! A short introduction on how to create an app

Link old Xcode with the new SDKs

Finding closest locations with GKRTree in Swift

Applying Auto-Layout to UIScrollView in Code

ionic: ios simulator/device not compiling SCSS but working in Android and web

Emotion Recognition on iOS Device with Empath

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suneet Agrawal

Suneet Agrawal


More from Medium

Pulling real time data with WebSocket and SwiftUI

Access specifiers in Swift

iOS Stack Weekly — Issue #9

Odometer reading input in Swift