Swift 5: Fallthrough Used-Cases You Must Know
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:
- If the user is suspicious, we will sign him/her out;
- If the user is unauthorized, we will sign him/her in, retrieve the location and the weather;
- 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.