Swift

Switch Case

A quicker If Statement

What is a switch?

A switch is similar to having tons of if statements. They match a case to a value, and determine a result based on that. Here is an example:

let dogs = 3 // let is the same as var, except we cannot change it letter, it is a constant
switch dogs {
    case 0: print("You have no dogs!")
    case 1: print("You have a dog!")
    case 2: print("You have two dogs!")
    case 3: print("You have lots of dogs!")
    default: print("Dogs?")
}

Understanding Switches

Let’s explain this. When we write switch dogs, we are letting the switch know we want to check the value of dogs. Each case is a value we check. Case 0 is the same as writing if dogs == 0. It’s a lot faster, and helpful when checking tons of different values. In this switch we check for 0,1,2,3. The default case at the end is for any value that isn’t 0,1,2,3. Consider it like the else statement. We can also introduce some more conditions, similar to using ||.

let pets = 2.5
switch pets {
    case 0,1: print("You have little to no pets!") // either 0 or 1
    case 2...4: print("You have a few pets!") // between 2 and 4 (floating points work!)
    default: print("What are pets?")
}
chevron_up