Why Switch Statements
Switch statements work the same as if statements but they help to make code more readable. Switch statements work well with enumerations and allow you to iterate all cases.
switch directionToGo {
case .north:
print("go north")
case .south:
print("go south")
case .east:
print("go east")
case .west:
print("go west")
}
Using if statements, this is how it would look like.
if directionToGo == .north {
print("go north")
} else if directionToGo == .south {
print("go south")
} else if directionToGo == .east {
print("go east")
} else if directionToGo == .west {
print("go west")
}
Handling Cases
Break
In a switch statement, the cases have to be exhaustive. You need to ensure all cases are handled for.
If you do not intend on executing code in a particular case, you can use the break
keyword.
switch directionToGo {
case .north:
print("that's the right direction!")
case .south:
break
case .east:
break
case .west:
break
}
Default
The default in a switch statement is similar to the else clause of an if statement.
switch directionToGo {
case .north:
print("that's the right direction!")
default:
print("wrong way!")
}
Multiple Cases
You can incorporate multiple cases in one by separating them with commas.
switch planet {
case .earth:
print("That's where we are!")
case .mercury, .venus, .mars:
print("Rocky planets")
case .jupiter, .saturn, .uranus, .neptune:
print("Gas giants")
}
Ranges
For data types like integers and doubles, you can use ranges for cases.
let number = 10
switch number {
case 0...5:
print("it's a number from 0 to 5")
case 6:
print("it's 6")
case 10..<100:
print("between 10 and 100")
default:
print("that’s a number. yay.")
}
Some
Switch statements allow you to handle the optional value using the .some
case. You can also use it to check the wrapped value against other values.
In this example, the wrapped value, optionalNumber
is checked against 42, then it is optionally bounded to the value
property in the .some(let value)
case. Finally, the default case handles any nil values.
let optionalNumber = Int(userFavoriteNumber)
switch optionalNumber {
case 42:
print("The answer to the ultimate question of life, the universe, and everything")
case .some(let value):
print("Your favorite number is \(value)")
default:
print("Handle if the optionalNumber is nil")
}
In the above example, the default case can also be replaced with case nil:
to handle missing values.
Switch Statements & SwiftUI
Switch statements work well in SwiftUI to conditionally render.
struct ContentView: View {
@State private var planet: Planet = .earth
var body: some View {
VStack {
switch planet {
case .earth:
Image(systemName: "house")
case .mercury, .venus, .mars:
Text("Rocky planets")
case .jupiter, .saturn, .uranus, .neptune:
Text("Gas giants")
}
Button("Another Planet!") {
planet = Planet.allCases.randomElement()!
}
}
}
}
Using a switch statement and an enumeration can be a good way to manage your app's state.
An enumeration can be created with the various app phases, for instance, in a game, you may have states like instructions, loading, playing, and game over.
enum AppPhase {
case instructions
case loading
case playing
case gameOver
}
In the app's ContentView
, the phase can be used within a switch statement to display the various phases in a clean, readable way.
struct ContentView: View {
@State private var phase = AppPhase.loading
var body: some View {
switch phase {
case .instructions:
InstructionsView()
case .loading:
LoadingView()
case .playing:
PlayingGameView()
case .gameOver:
GameOverView()
}
}
}