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

Appium setup for iOS application

Singleton vs Dependency Injection in Swift

Extending the new WinDbg, Part 2 — Tool windows and command output

Does The Swift Programming Language Help In Developing Dynamic iOS Apps?

Handling iOS locator with Appium more efficiently

Pera Wallet iOS 5.0.4 Release Changelog

Finding closest locations with GKRTree in Swift

How to create custom Header and Footer view for tableview using xib in swift?

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

Swift Dictionary and Set and its time complexity — Data Structure

Convert string of integers to an Int: w/o Int(“1234”, radix:10) — iOS Swift

apple/swift-evolution 上關於 guard 的有趣討論

Swift: The different between try, try? and try!