The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.Source
But its behaviour seems to vary across types, with Array being the noticeable outlier:
let xs = [0, 1, 2]
_ = xs.index(xs.endIndex, offsetBy: 1, limitedBy: xs.startIndex)
// Prints "Optional(4)"
let xs = 0...2
_ = xs.index(xs.endIndex, offsetBy: 1, limitedBy: xs.startIndex)
// Crashes with message "Fatal error: Advancing past end index"
let xs = Set([0, 1, 2])
_ = xs.index(xs.endIndex, offsetBy: 1, limitedBy: xs.startIndex)
// Crashes with no message
let xs = [0: "a", 1: "b", 2: "c"]
_ = xs.index(xs.endIndex, offsetBy: 1, limitedBy: xs.startIndex)
// Crashes with no message
let xs = [0: "a", 1: "b", 2: "c"].keys
_ = xs.index(xs.endIndex, offsetBy: 1, limitedBy: xs.startIndex)
// Crashes with no message
To me it seems like it currently follows the following behaviour:
- Trap when the offset
i does not pass limit, but is out of bounds.
return nil when the offset i passes limit, regardless of whether or not it is out of bounds.
return an Optional value if it doesn't pass limit and is in bounds.
Is this correct? And if so, wouldn't Array's implementation be incorrect then?