What does a Relative Range Contain?

So suppose I'm making a range that has relative offsets, such that 2..<-2 would get the elements after the 2nd element of a collection up to but before the last 2 of the collection.

let x = [0, 1, 2, 3, 4, 5, 6, 7]
x[offset: 2..<-2] // [3, 4, 5]

I have a type that represents this range, and I want to make it conform to RangeExpression. I can implement relative(to:) fine, but contains has me stumped. Any idea's how this would work? What should the semantics be here? If there are any reasonable ones.

I don't think you can make this type conform to RangeExpression, exactly because contains doesn't take a collection to measure containment "relative to".

But I don't think it would be appropriate for this to be a RangeExpression anyway, because then you could use it directly with the argument-less range subscript (which is what RangeExpression was created for). And that would be contrary to the goal of being able to use/require it be used with subscript(offset:).

That said, I think it's good for it to have a relative(to:) method, even if it's not there for protocol conformance purposes.

1 Like

Put another way: contains is on RangeExpression mainly to support ~= for switch statements e.g.

switch i {
case 1...: print("at least 1")
case ...10: print("no more than 10")
}

In the above example, it's not clear what case 2..<-2 would mean.

1 Like