Comment on page

# Ranges

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

`Double`

s and `Float`

s, 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 `Sequence`

protocol. 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:

`contains`

and `isEmpty`

. For those that are interested or want a second explanation, you may find Apple's documentation to be helpful:Apple Developer Documentation

Range Documentation

Apple Developer Documentation

Closed Range Documentation

Last modified 1yr ago