The switch
statement’s ability to match values to an expression that exist within intervals is one of its superpowers. An interval matching in Swift is a range, that can use to see if a given value falls within it.
A range is represented in Swift by three consecutive dots,...
, also known as the closed range operator. The closed range operator denotes a range that includes both the first and last values in the sequence.
Let’s take a look at how these new ideas work in practice. The switch
statement in the example below determines the value of age
and checks which stage it belongs to.
var age = 17;
switch age {
case 1...3:
print("Toddler");
case 3...5:
print("Preschool");
case 5...12:
print("Gradeschooler");
case 12...18:
print("Teen");
default:
print("You're Young Adult!");
}
// Prints: Teen
Since the age, 17
, falls between the interval, 12...18
, the code for the fourth case is executed and the message, Teen
gets printed.
Here are some useful tools to help you along your journey!
Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.