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
AnySequenceinstance[…] This code works, but it’s not a nice generic solution, especially for types that also conform toCollection. Wrapping the tail in anAnySequenceis a big performance killer, and you can’t use the affordances of a collection’s properSubSequencetype.[…]
Dennis’s trick is to call
Sequence.drop(while:), which preserves theSubSequencetype 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
SubSequencetype, only collections (Swift Evolution proposal SE-0234).