Exploring Range Operators
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
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.
For more information on range operators, visit: https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html.
Let’s try this out in the playground. Follow these steps:
- Add the following code to your playground and click the Play/Stop button to run it:
let myRange = 10...20
This will...