Swift 5: Fallthrough Used-Cases You Must Know

Swiftos
Geek Culture
Published in
4 min readMar 13, 2021

--

Photo by Jörg Angeli on Unsplash

Hi iOS Devs,

In general, switch statements only execute one case. If we want to continue the execution to the next case, we can use the fallthrough keyword. Today, I’ll talk about the most common used-cases of fallthrough.

Case 1

Let’s say we’re developing a weather app. We need to check the authorization status. Based on what we find out about status, here’s what we’ll do:

  1. If the user is suspicious, we will sign him/her out;
  2. If the user is unauthorized, we will sign him/her in, retrieve the location and the weather;
  3. If the user is authorized, we will retrieve the location and the weather.

Let’s see what we’d do if we didn’t have the fallthrough keyword.

enum AuthStatus {
case authorized, suspicious, unauthorized
}
let authStatus: AuthStatus = .unauthorizedswitch authStatus {
case .suspicious:
signOut()
case .unauthorized:
signIn()
getLocation()
getWeather()
case .authorized:
getLocation()
getWeather()
}

As you can see, we have some duplicated code here, the getLocation and the getWeather because we need them both.

--

--

Swiftos
Geek Culture

I publish short iOS development tutorials on a weekly basis. For all content, head over to: https://www.patreon.com/Swiftos