The value passed as
distancemust not offsetibeyond the bounds of the collection, unless the index passed aslimitprevents 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
idoes not passlimit, but is out of bounds. returnnilwhen the offsetipasseslimit, regardless of whether or not it is out of bounds.returnanOptionalvalue if it doesn't passlimitand is in bounds.
Is this correct? And if so, wouldn't Array's implementation be incorrect then?