Comment on page
Ranges are a data type the specifies a list of numbers over which to execute–it's exactly what it sounds like. This is analogous to ranges in math. [1, 2] species all numbers between 1 and 2 inclusively. The one difference from mathematical ranges is that we must include the lower bound. A normal, inclusive range, is written
<lower bound>...<upper bound>. This is called a closed range. To exclude the upper bound, we write
<lower bound>..<<upper bound>. That's looking kind of gross with my formatting so let's show some code.
let myInclusiveRange = 0...1
// myInclusiveRange: ClosedRange<Int> which is equivalent to [0, 1]
let myExclusiveRange = 0..<1
// myExclusiveRange: Range<Int> which is equivalent to [0, 1)
let myFailingRange = 1...0
// Fatal error: Range requires lowerBound <= upperBound
You can technically do this with both
Floats, but I have never had a use for it. You will most often use ranges for loops or indexing into arrays. For this to happen, the range must conform to the
Sequenceprotocol. Jargon aside, this just means that it must be easily convertible to a list of numbers in that sequence. With decimals, the program doesn't know where to draw the boundaries, so this doesn't work. Hence, ranges are most often constructed with integers.
Ranges have two more properties that may be of use:
isEmpty. For those that are interested or want a second explanation, you may find Apple's documentation to be helpful: