You’ve mainly likely heard of an if statement, consider of switch cases to be the more advanced form of a if.
To begin a switch statement you inform Swift what variable you want to run things by, and then give the list of possible cases.
Swift will get the case that matches your code first and then perform it then exit the switch.
Here’s a simple example:
let someNumber = 150 switch someNumber { case 150: print("Number is 150") default: print("Otherwise, do something else.") }
Even if you think you know your cases will always be performed, you require to have the default: to fall back on.
Multiple Cases
Let’s include more cases and utilize some more types of conditions.
We have a number like last time, though this time we will ensure for a range of numbers in each case.
Like so:
let someNumber = 150 switch someNumber { case 0...50: print("Number is between 0 & 50") case 51...100: print("Number is between 51 & 100") case 101...150: print("Number is between 101 & 150") default: print("Fallback option") }
To ensure for a range you simply use three periods like so:
1…100
Nothing has changed really since the first one.
We included more cases along with verfying for a range of numbers just to exhibit what you can do in a case.
Leave a Reply