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 would be much more convenient if there was a way to specify a range of numbers, and that is what a range operator does.
Important information
For more information on range operators, visit https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html.
Let's say you want to represent a sequence of numbers from 10 to 20. You don't need to specify every value; you can just specify the first number and the last number in this way:
firstNumber...lastNumber
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 assign a number sequence that starts with
10
and ends...