Programming in Swift: Functions & Types

Jan 4 2022 · Swift 5.5, iOS 15, Xcode 13

Part 3: Enumerations

23. Switch Statements

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 22. Challenge: Enumerations Next episode: 24. More Switch Statements

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 23. Switch Statements

Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.

Transcript: 23. Switch Statements

At this point, you’re familiar with a few different ways of controlling the flow of execution in your apps: if statements, while loops, and for loops. Now, you’ll learn about one more method of control flow: switch statements.

Switch statements in Swift are very powerful. If you’ve programmed in other languages, you might be surprised at what they can do. Let’s start by seeing how a switch statement can help us deal with enumerations.

At the top of this playground page, I’ve got our Month and Season enumerations from earlier in this part.

What if we wanted to figure out what season any given month is in? Maybe we’d put that in a function called something like getSeason

func getSeason(

it would have one parameter, a Month, and return whatever Season that month is in.

(for month: Month) -> Season {

}

How might we actually figure that out, though? We could try using an if statement with some else clauses. If the month is december

if month == .december

or if the month is january or if the month is february…

.december || month == .january || month == .february {

}

Then we’d return winter as the season

return .winter

That’s already getting pretty tedious, and we’ve only done one season. A switch statement can help make this a little easier to deal with. So, delete all of that and start with the keyword switch

switch 

and the value we’re going to switch on is whatever month was passed into this function.

switch month 

and then you open up the switch statement with a pair of curly braces.

switch month {

}

I think of this as saying “Switch what happens based on the value of month”.

This is often referred to as switching “on” that value. So here, we’re “switching on month”. Try not to get confused with that common phrasing – it doesn’t have anything to do with “switching on”, the way you might a light bulb. Now, let’s say, in the case where the month is december…

case .december

Return winter from this function

case .december😺:
  return .winter

The keyword “case” is used differently here, than inside an enumeration. In Switch statements, “case” is used in sort of the same way you’d use “if” and “else if” in if statements.

But in a switch statements it’s much easier to just say “when the value we’re switching on is any of these things, do something.” You just comma separate the possible values.

case .december, .january, .february:

That’s called a compound case, and hopefully you can see one reason I’d recommend using a switch statement over an if statement for this function!

Let’s take a short break and look at the syntax and formatting going on here, because it’s a bit different than other constructs in Swift.

One thing to note, is that you’ll usually see a switch statement’s cases line up with the switch keyword, and the statement’s closing brace.

This might seem kind of strange when you first see it, because otherwise, people tend to format their code with one more level of indentation inside of curly braces.

switch statements have a different convention. But they’ll actually compile either way. So, indent if you prefer.

Also, notice that this colon comes at the end of the list of values. It denotes the start of the body of the case. And just as you might expect, any code inside the body will execute when any of those values are the one we’re looking for.

Even though there aren’t curly braces, the body still acts as a local scope for each “case”. We’ll make more use of that idea a little later.

Now, I’m going to turn on a setting that I switched off, because it can cover things up during demo recording that I don’t want covered up. But I want to show you how it can help you out with switch statements, so I’m going to turn it back on now!

To get there, I’ll go to Xcode - Preferences. Or I could hit Command - comma, and under the General tab, I’ll check “Show live issues”

And then Christine, one of our video editors, is going to magically splice my two recordings together because I had to restart Xcode for that setting to take effect, and, frankly, my computer crashed. Thanks Christine!

You may have been wondering why you’ve had a bunch of yellow and red notes and I haven’t. Now you know why!

nd now I do have this red warning on the side telling me that the Switch must be exhaustive!

That means it has to account for all possible values that month might be. When you’re switching on an enum value, that’s easy! In fact, the compiler can help you do it. You can use the switch statement on types that aren’t enums, but we’ll get to that a little later.

Right now, click the red octagon, here, and click “Fix” to say “Why, yes, I do want you to add those missing cases for me!”

  case .march:
    <#code#>
  case .april:
    <#code#>
  case .may:
    <#code#>
  case .june:
    <#code#>
  case .july:
    <#code#>
  case .august:
    <#code#>
  case .september:
    <#code#>
  case .october:
    <#code#>
  case .november:
    <#code#>
  }

Wow! That’s not exactly what we want, but I can use it as a starting place and delete the bits I don’t need. I’ll collect all the spring months in one case…

case .march, .april, .may:
    return .spring

Then summer…

case .june, .july, .august:
    return .summer

and finally, autumn.

case .september, .october, .november:
    return .autumn

If you live in a different part of the world, feel free to change which months go with which seasons. Maybe december is summer for you! Or maybe it’s reasonable to say your winter lasts from november through may.

As long as you account for all of the months, all of the errors and warnings should be gone and we can try calling this function! Pass in any month you like.

getSeason(for: .august)

And run the playground! August means summer for me!

There’s a way we can turn this function into a method or property of Month, but we’ll come back to that in the next part of the course. There’s also a lot more you can do with switch statements! And we’ll explore that in the next episode.