Beta 6: Slice indices, zero, and what Beta 6 doesn’t change #swiftlang

This keeps coming up today, so I thought I’d add a post. In beta 6, Apple writes, “For consistency and better composition of generic code, ArraySlice indices are no longer always zero- based but map directly onto the indices of the collection they are slicing and maintain that mapping even after mutations.

That means if you create a slice of a collection, you can still use the original indices with that slice.

Fast forward to today. In today’s post about counting from n, I wrote about zero-based slice enumerations. The public responded:

So what’s going on? While the slice retains its indices, an enumeration over the slice does not. You can see this yourself in the following screenshot:

View post on

This happens because the enumeration is index-agnostic. An enumeration produces a sequence, and not a collection. Sequences are zero-based as they iteratively generates elements.

And here’s a workaround:

Hope this helps.

Comments are closed.