masters3d masters3d - 4 months ago 12x
Swift Question

What are "intervals" in swift ranges?

I know there are 3 types of ranges: Range, Strides and Intervals.

var closed:ClosedInterval = 1.2...5.0

var half_open:HalfOpenInterval = 1.2..<5.0

What are intervals in swift? and what is one example of their use?

This is what the beta 5 xcode 6 release notes says:

• Intervals over Comparable values, which can efficiently check for containment. Intervals are
used for pattern matching in switch statements and by the ~= operator.


As of Swift 3 (currently in beta with Xcode 8 beta, and in progress with the Swift open source community), the Interval types are no more. Now the family of Range<T> types include the functionality of both the former range and interval types, and additionally conform to the new model for collection types and indices.

In Swift 2.x and older... Ranges are for iterating, and Intervals are for pattern matching.

func testNum(num: Int) {
    let interval: HalfOpenInterval = 0..<10
    let range = 10..<20
    switch num {
    case interval:    // this works
    case range:       // error "does not conform to protocol IntervalType"

A Range type is optimized for generating values that increment through the range, and works with types that can be counted and incremented.

An Interval type is optimized for testing whether a given value lies within the interval. It works with types that don't necessarily need a notion of incrementing, and provides operations like clamping one range to another (e.g. (0..<10).clamp(5..<15) yields 5..<10) that are useful for complex pattern matching.

Because the ..< and ... operators have two forms each--one that returns a Range and one that returns an Interval--type inference automatically uses the right one based on context. So, if you write 0..<10 in a case label of a switch statement, Swift automatically constructs a HalfOpenInterval because a switch statement requires an Interval type.

The ~= operator is a way to do one test on an interval without a switch statement. Writing interval ~= value is equivalent to interval.contains(value).

It's worth noting that you can find out many of these things by looking at the standard library interface and its comments: write a type name like HalfOpenInterval in a playground, then command-click to jump to its definition.