Creating a CollectionOfOne from a Sequence element

Yeah I think Sequence is a bit of a useless protocol - it doesn't model the thing it is supposed to model (single-pass collections, with no notion of position) very well, and as it happens, the thing "above" it in the collection hierarchy (IteratorProtocol) models that same thing much better. Multi-pass sequences always have some notion of position, so Collection is a much better fit.

The reason Sequence exists is so that you can write for loops over both single and multi-pass sequences. Personally, I have no idea why that was felt to be an important feature in the language, and my rule of thumb is actually to avoid it entirely for generic code: if you can, use Collection, otherwise, use an inout IteratorProtocol.

Consider a super-simple snippet like sequence.prefix(2); sequence.prefix(2) (reading the first 2 elements, twice). This could yield [1, 2], [1, 2], or it could yield [1, 2, 3, 4] depending on implementation details your generic algorithm can't possibly know. Any other place in the collection hierarchy gives you consistent results - iterators always consume their elements (so reading the first 2 elements, twice, always yields [1, 2], [3, 4]), and accessing Collection elements by their indexes never consumes them (so the same operation always yields [1, 2], [1, 2]).

1 Like