Exploring range operators
Imagine you need to write a program for a department store that automatically sends a discount voucher to customers between the ages of 18 and 30. It would be very cumbersome if you needed to set up an if
or switch
statement for each age. It’s much more convenient to use a range operator in this case.
Range operators allow you to represent a range of values. Let’s say you want to represent a sequence of numbers starting with firstNumber
and ending with lastNumber
. You don’t need to specify every value; you can just specify the range in this way:
firstNumber...lastNumber
For more information on range operators, visit: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/basicoperators.
Let’s try this out in the playground. Follow these steps:
- Add the following code to your playground and click the Run button:
let myRange = 10...20
This will assign a number...