One of the strengths of using the switch
statement is pattern matching. Say you have a set of values you wanted to check using switch
, the compiler will make sure you get to cover an exhaustive
list of cases that correspond to all possible values.
This is to make sure that you won’t miss anything, and if you do, the Swift compiler will tell you. This is one of the differences between using switch
instead of if
.
When you use if
, the compiler won’t be strict in reminding you that you need to check for an exhaustive list of values, but rather gives you the flexibility to only check what you need.
So if you have a set of values you want to check for matches, the best conditional statement to use is the switch
statement.
For example, you have an Enumeration about all of the planets in the Solar system, and you wanted to perform a switch statement over an enum variable such as follows:
enum Planet { case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune } let planet: Planet = .earth switch planet { case .mercury: print("The planet closest to the sun") case .earth: print("This is where we live") case .neptune: print("The planet farthest from the sun of the Solar system") }
Write the code above, and you’ll get a compiler error Switch must be exhaustive
. This is the way the Swift compiler tells you that you need to take into account all possible values.
So what you can do is either click on the error and choose “Add missing cases”, which will then add more switch cases
for all remaining values of the Planet
enum, or you can choose to ignore the error and add a default
case.
Option 1: Adding missing cases
When you choose to “Add missing cases”, the Swift compiler will add all remaining switch cases for you. This would make it easier to complete the exhaustive list of switch cases for you to handle.
switch planet { case .mercury: print("The planet closest to the sun") case .earth: print("This is where we live") case .neptune: print("The planet farthest from the sun of the Solar system") case .venus: addcode case .mars: addcode case .jupiter: addcode case .saturn: addcode case .uranus: addcode }
Option 2: Adding a default case
You can also add a default
case if you choose not to do an exhaustive list of cases.
switch planet { case .mercury: print("The planet closest to the sun") case .earth: print("This is where we live") case .neptune: print("The planet farthest from the sun of the Solar system") default: print("A planet inside the Solar system.") }
Both options work, but for added safety, I would recommend opting for an exhaustive list of switch cases. This way you also get to use the built-in Swift compiler safety features.
That’s all for now! See you on the next one!