Splitting a Swift Sequence Into Head and Tail
One possible solution is to create an iterator to read in the first element, and then wrap the current iterator state in a new
AnySequence
instance[…] This code works, but it’s not a nice generic solution, especially for types that also conform toCollection
. Wrapping the tail in anAnySequence
is a big performance killer, and you can’t use the affordances of a collection’s properSubSequence
type.[…]
Dennis’s trick is to call
Sequence.drop(while:)
, which preserves theSubSequence
type for the tail, and then “catch” the first element inside thedrop(while:)
predicate closure using a captured local variable. Nicely done![…]
The code above targets Swift 4.2. It will break in Swift 5 because sequences will no longer have an associated
SubSequence
type, only collections (Swift Evolution proposal SE-0234).