/

Swift Conditionals: Using the `switch` Statement

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
2
3
4
5
6
7
8
var name = "Roger"

switch name {
case "Roger":
print("Hello, Mr. Roger!")
default:
print("Hello, \(name)")
}

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
2
3
4
5
6
7
8
9
10
11
12
13
enum Animal {
case dog
case cat
}

var animal: Animal = .dog

switch animal {
case .dog:
print("Hello, dog!")
case .cat:
print("Hello, cat!")
}

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
2
3
4
5
6
7
8
var age = 20

switch age {
case 0..<18:
print("You can't drive!")
default:
print("You can drive")
}

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.