Tuesday, January 1, 2019 [Tweets] [Favorites]

Splitting a Swift Sequence Into Head and Tail

Ole Begemann:

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 to Collection. Wrapping the tail in an AnySequence is a big performance killer, and you can’t use the affordances of a collection’s proper SubSequence type.

[…]

Dennis’s trick is to call Sequence.drop(while:), which preserves the SubSequence type for the tail, and then “catch” the first element inside the drop(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).

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment