Switch Statements using Swift

Press the switch on or off

Here the image of a Switch represents two states, either on or off. In Swift Switch statements allow us to have an alternative to If statements to choose between two (or more) options.

Although Switch statements are relatively easy, there are a number of prerequisites for this article. Make sure you read up, and then get going on this guide!

Image for post
Image for post
Photo by twinsfisch on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)
  • Protocols in Swift (guide HERE)
  • A grasp of enum would be useful (guide HERE)
  • It would be useful to be familiar with String Interpolation (guide HERE)
  • Tuples are featured later on, but you are shown how to create them, and underscores are used to ignore Tuple Components (guide HERE)
  • Networking responses are mentioned, but this is only to give context and is not essential to this guide

Terminology

Enum: A type consisting of a set of named values, called members

Fallthrough: Fall through the bottom of each case and into the next one

Instance: An example or single occurrence of something

Switch: A switch statement is a selection control mechanism to change the control flow of a program

Tuple: A way in Swift to allow you to store multiple values in a single variable

Switch with an enum

We set up an enum with the Seasons.

enum Season {
case winter
case spring
case summer
case autumn
}

and then we can set up an instance of this enum

let happy = Season.summer

Then we can switch on this instance

switch happy {
case .winter:
print ("Winter")
case .spring:
print ("Spring")
case .summer:
print ("Summer")
case .autumn:
print ("Autumn")
}

Nice! This isn’t as hard as one might think.

Exhaust your Switch

If you don’t cover all the cases, the Swift compiler will display a passive-aggressive error:

switch must be exhaustive

So, thanks Swift. We’ll solve that.

switch emotion {
case .happy:
print ("Happy")
case .sad:
print ("Sad")
case .anxious:
print ("Anxious")
default:
print ("Either scared or ill")
}

The default case is, well a default. You don’t have to explicitly have a path for every case, you can use default to do that for you.

Compound cases

A compound cases means that we can combine cases. Continuing the emotion example

switch emotion {
case .happy:
print ("Positive emotion")
case .anxious, .sad, .ill:
print ("Negative emotion")
}

So we can bundle the cases together. A handy tool for us programmers!

Fallthrough

By default Swift switches do not fallthrough. That is, as in the above example if the emotion is happy it will print Positive emotion. Once it has done that it won’t go to the next case, that is it won’tfallthrough. For this example I’ve set up a different enum that (very) loosely represents the App states (for a full list, look at this rather great article)

enum State {
case background
case active
case suspend
}
let state = State.background

with an accompanying Switch

switch state {
case .active:
print ("Active App")
case .background:
print ("Background App")
fallthrough
default:
print ("App not active")
}

Which outputs both “Background App” and “App not active”

A Switch using Interval Matching

A simple use of interval matching might be using networking. Let us see the example:

let serverResponse = 200switch serverResponse {
case 200 ..< 300:
print ("Valid response")
default:
print ("Error response")
}

so what we are saying here is that any response in the range 200 … 299 is valid. We used a case statement to be able to do it. Awesome!

Switch statements and Tuples

We can create a Tuple

let james = ("James", "Cameron")

With the related switch case

switch james {
case ("James", "Cameron"):
print ("JC")
fallthrough
case ("James", _):
print ("James")
case ("James", "Willis"):
print ("JW")
default:
print ("Not JS")
}

or we can do the following:

let person = ("Dave", 28)
switch person {
case (let x, 28):
print (x0
default:
print ("Not found")
}

Or even using where:

let shopping = ("beans", 20, 4)switch shopping {
case let (x, y, z) where y/20 > 1:
print ("Expensive \(x)")
default:
print ("Cheap")

Conclusion:

Switch statements are great for picking between a selection of choices, often closely linked to enum. Think about old-school adventure games where you could move North, South, East or West. Sounds like a good use for an enum linked to a switch statement.

Oh, and you’ll also find yourself doing this when you end up using networking.

As ever, this is a tool for your programming toolbox. You have the ability to do new things here, but you have to decide where to apply them according to your problem.

As ever, happy coding.

Extend your knowledge

  • Want to know more about Tuples? Follow the link HERE

The Twitter contact:

Any questions? You can get in touch with me here

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