Closed rudedogdhc closed 2 years ago
This is the expected behavior, if I’m understanding the point correctly.
Not all collection indices start at 0
, and indeed they don’t need to have indices of type Int
. However, when you obtain a slice of a collection (as in this case for chunks), that slice shares indices with its parent. When you attempt to access the element of a slice at index 1
, this is supposed to be out of bounds if the slice doesn’t include the parent collection’s element that’s at index 1
.
There isn’t anything specific to ChunksOfCountCollection
but rather common to all of Swift. Understanding this point is key to using indices correctly.
You are correct and I've learned something new about Swift. Using $0.count == 2 ? $0[$0.startIndex + 1] : nil
is the proper way to do this.
Using
$0.count == 2 ? $0[$0.startIndex + 1] : nil
is the proper way to do this.
index(_:offsetBy:)
exists to do this. This would work for indices that aren’t Int
and those that might not count by 1s.
Replace this paragraph with a short description of the incorrect incorrect behavior. If this is a regression, please note the last version that the behavior was correct in addition to your current version.
Swift Algorithms version:
main
branchSwift version:
Checklist
main
branch of this packageSteps to Reproduce
The following code crashes:
Expected behavior
It shouldn't crash. Each chunk has a count of 2 so accessing a chunk with index 1 should not crash.
Actual behavior
It crashes. If I uncomment the conversion back to
Array
it works fine. Based on some testing, the crash appears to happen with every sub-chunk after the first one.