Welcome back! In this lesson, we'll explore the switch statement with ranges in Swift. This powerful construct will help you make decisions based on the value of a variable, and it's especially useful when you're dealing with numerical data. Let's dive in!
switch statement? 📝The switch statement is a control structure that allows you to compare a value against multiple cases. It's a useful tool for making decisions based on the value of a variable.
switch 💡In Swift, you can make your switch statements even more powerful by using ranges. This allows you to match a value within a given range of numbers, rather than just exact matches.
switch with Ranges 📝Here's the basic syntax for using ranges in a switch statement:
switch expression {
case range1:
// code to execute if expression is within range1
case range2:
// code to execute if expression is within range2
...
default:
// code to execute if none of the cases match
}In Swift, you can create a range using the ... operator. The range includes both start and end points.
let start = 1
let end = 5
let range = start...endNow, range is a range from 1 to 5, inclusive.
switch 📝Let's look at a simple example of using ranges in a switch statement:
let number = 3
switch number {
case 1...3:
print("Small number")
case 4...6:
print("Medium number")
case 7...10:
print("Large number")
default:
print("Number out of range")
}In this example, if number is equal to 3, the output will be "Small number".
Here's a more complex example that demonstrates the power of using ranges in a switch statement:
let grade: Double
let gradePoints: [Double: String] = [
4.0: "A+",
3.75: "A",
3.0: "B",
2.0: "C",
1.0: "D",
0.0: "F"
]
// Assign a grade
grade = 3.5
// Use switch to determine the grade letter
switch grade {
case let grade where grade >= 4.0:
gradePoints[grade]
case let grade where grade >= 3.75 && grade < 4.0:
"A-"
case let grade where grade >= 3.0 && grade < 3.75:
"B+"
case let grade where grade >= 2.0 && grade < 3.0:
"C+"
case let grade where grade >= 1.0 && grade < 2.0:
"D+"
default:
"F"
}
// Print the grade letter
print(gradePoints[grade] ?? "Invalid grade")In this example, we're using a Dictionary (gradePoints) to map numeric grades to their respective letter grades. We're also using the ternary operator (where) to check for ranges and return the appropriate letter grade.
What is the output of the following code?
That's it for today! In the next lesson, we'll continue exploring Swift by diving deeper into control structures. Keep practicing, and happy coding! 🚀