Video
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.
Using if statements, this is how it would look like.
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.
Default
The default in a switch statement is similar to the else clause of an if statement.
Multiple Cases
You can incorporate multiple cases in one by separating them with commas.
Ranges
For data types like integers and doubles, you can use ranges for cases.
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.
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.
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.
In the app's ContentView
, the phase can be used within a switch statement to display the various phases in a clean, readable way. To learn more about this, check out Conditional Rendering.
In These Collections
This article can also be found in these collections.