What Does The relative(to:) Function Actually Do?

Viewed 583

This is from the Swift Standard Library Documentation:

relative(to:)

Returns the range of indices within the given collection described by this range expression.

Here is the method signature:

func relative<C>(to collection: C) -> Range<Self.Bound> where C : _Indexable, Self.Bound == C.Index

Along with its explanation:

Parameters

collection

The collection to evaluate this range expression in relation to.

Return Value

A range suitable for slicing collection. The returned range is not guaranteed to be inside the bounds of collection. Callers should apply the same preconditions to the return value as they would to a range provided directly by the user.

Finally, here is my test code:

let continuousCollection = Array(0..<10)
var range = 0..<5
print(range.relative(to: continuousCollection))
//0..<5
range = 5..<15
print(range.relative(to: continuousCollection))
//5..<15
range = 11..<15
print(range.relative(to: continuousCollection))
//11..<15
let disparateCollection = [1, 4, 6, 7, 10, 12, 13, 16, 18, 19, 22]
range = 0..<5
print(range.relative(to: disparateCollection))
//0..<5
range = 5..<15
print(range.relative(to: disparateCollection))
//5..<15
range = 11..<15
print(range.relative(to: disparateCollection))
//11..<15

In every case, relative(to:) just returns the original range. What is this method supposed to do?

1 Answers
Related