Hey Swift, how many Range types do you need ?

I was messing around with the random number generator code for Int and noticed that the API has two Range types, Range and ClosedRange. Upon further investigation I found that Swift supports even more range types.

So currently the range types are Range, ClosedRange, PartialRangeFrom, PartialRangeUpTo, PartialRangeThrough and CountableRange.

Range

The Range type is “a half-open interval from a lower bound up to, but not including, an upper bound”. Which basically means the ..< syntax, i.e.

let range = 1..<100

In other words range is from (and including) 1 to 100 (but not including 100).

We might write a function to handle this using the following syntax

// usage rangeTest.range(1..<10)
func range(_ r: Range<Int>) -> Void {
  print("\(r.lowerBound), \(r.upperBound)")
}

ClosedRange

The ClosedRange type is “an interval from a lower bound up to, and including, an upper bound”. Which basically means the … syntax, i.e.

let range = 1...100

In other words range is from (and including) 1 to 100 (and including 100).

We might write a function to handle this using the following syntax

// rangeTest.range(1...10)
func range(_ r: ClosedRange<Int>) -> Void {
  print("\(r.lowerBound), \(r.upperBound)")
}

PartialRangeFrom

The PartialRangeFrom type is “a partial interval extending upward from a lower bound”. Which uses … syntax, i.e.

let range = 0...

We might write a function to handle this using the following syntax

// rangeTest.range(..<10)
func range(_ r: PartialRangeUpTo<Int>) -> Void {
  print("\(r.lowerBound)")
}

PartialRangeUpTo

The PartialRangeUpTo type is “a partial half-open interval up to, but not including, an upper bound”. Which uses ..< syntax, i.e.

let range = ..<100

We might write a function to handle this using the following syntax

// rangeTest.range(..<10)
func range(_ r: PartialRangeUpTo<Int>) -> Void {
  print("\(r.upperBound)")
}

PartialRangeThrough

The PartialRangeThrough type is “a partial interval up to, and including, an upper bound”. Which uses the … syntax, i.e.

let range = ...100

We might write a function to handle this using the following syntax

// rangeTest.range(...10)
func range(_ r: PartialRangeThrough<Int>) -> Void {
  print("\(r.upperBound)")
}

CountableRange

The CountableRange is just a type alias around a Range