Swift Conditionals: Using the switch
Statement
tags: [“Swift”, “switch”, “conditionals”]
The switch
statement in Swift provides a convenient way to create a conditional structure with multiple options. It allows you to choose a code block to execute based on the value of a certain variable or expression.
Here’s an example of using the switch
statement to check the value of a variable named name
:
1 | var name = "Roger" |
In this example, if the value of name
is “Roger”, it will print “Hello, Mr. Roger!”. Otherwise, it will print “Hello, [name]”.
The switch
statement in Swift requires you to cover all possible cases. If the variable or expression can have any value, you need to add a default
case as a fallback option. This default case will be executed if none of the other cases match.
If you’re working with an enumeration, you can simply list all the options as individual cases:
1 | enum Animal { |
In this example, if animal
is .dog
, it will print “Hello, dog!”. If animal
is .cat
, it will print “Hello, cat!”.
You can also use a Range
as a case in a switch statement:
1 | var age = 20 |
In this case, if age
is in the range from 0 to less than 18, it will print “You can’t drive!”. Otherwise, it will print “You can drive”.
The switch
statement in Swift is a powerful tool for creating conditional logic with multiple options. It’s important to cover all possible cases and use a default case when necessary to ensure your code behaves as expected.