Case for a Switch
Working on Swift, I’ve come across a pretty cool little thing. I’ve been writing If/else statements for checking conditionals for a while. It’s one of the first things that anyone covers for flow control. You check to see if something is true or not and then act upon that check. Else you can do something different. But going into massive checks for lots of conditionals can be an eye sore.
You can also string together multiple If/Else if/Else statements for more complex checks:
That is a very boring example but the idea is there. You can string together multiple Else If statements for more complex flow control inside your application. But there has to be a cleaner way to do this, and there is! Swift gives us the Case Statement
Grand scheme of things, there is not a huge difference between my two examples. So why would you choose the Switch over the If/Else statement? For most conditional checks, the Switch statement should reduce the amount of code that you have to write. Let us take a more complex example and compare the two of them. Let us say we are checking for a number. We could write If/Else statements with multiple checks to see where that number is at but it could get really messy after a bit using “and” or “or” statements and nested If/Else If/Else statements to check for this number in the ranges we need. A Switch statement will check on multiple conditions and a range of conditions in a much cleaner syntax then the If/Else statement.
Oh, you see that Default check right at the bottom? I didn’t have that in my previous example. Why do I have it now? One thing on Switch statements is they have to be exhaustive. In our previous example, the conditional could be true or false and compiler was smart enough to know that. In the second example, we only check through 100. Well….there are a TON more numbers and we can’t go through them all. You may not always require a Default statement if your Switch syntax, an example would be Bool values or Enums. If your variable is an Enum then there can only be so many options for it to be, so the Switch can be exhaustive.
I hope you found this useful. If/Else statements have their place and do cool things for conditional workflows. Switch statements can be very powerful though and much easier to read or understand. Hop into your Xcode playgrounds and create a few of them and see what they can do and let me know what you find. I think these things are cool.