Sequences: The .next() Generator

Here’s a nice gentle introduction (h/t: This Week In Swift) to modelling an algorithmic collection using the SequenceType and GeneratorType protocols:

Sequences and Generators [EDIT: Disappeared!]

Let’s imagine, that we want to learn the new language. Spanish, for example. Your professor told you, that you will have one lesson each N days starting from today. But the bad thing – your professor doesn’t want to work on Sundays. So if the lesson is on Sunday, it will be rescheduled to the next day. We want to receive the schedule – Array<NSDate> for M days.

Grab the playground here, and walk through creating an NSDate sequence with

  1. A generator class for a defined number of iterations
  2. Using AnyGenerator for a bounded number of iterations
  3. A generator class for an infinite number of dates

along with using .prefix(), .filter() and .lazy() to make that infinite sequence actually usable in Swift 2, since filter() is no longer a free function like in Swift 1. More detailed explorations of laziness can be found here:

Being Lazy

True Lazy Sequences

Experimenting with Swift Sequences and Generators

And what do you get when you add indexability to a sequence? Why, a collection:

Swift Collections

Generic Collections, SubSequences and Overloading

For an application of the generator concept to a no doubt common modelling problem you’re presented with, check out

Practical Swift: pages generator – build once, use many

In the real world, at some point, we all have to deal with data that is fetched from a backend service, page by page. It’s called paging. Everybody does this! Nothing to be ashamed of 😉 Here is one of the ways in which a Swift pattern (well, not specific to Swift, but visible in Swift) can be used to build a neat solution that allows me to fetch data in chunks and display it in the application…

And finally, check out SwiftSequence, “A μframework of extensions for SequenceType in Swift 2.0, inspired by Python’s itertools, Haskell’s standard library, and other things,” for some handy manipulations:


Use as an alternative to recursion: Recursive Tail Calls and Trampolines in Swift

An algorithm reference will likely come in handy in this problem space: swift-algorithm-club

So might randomness: Random number generators in Swift

Swift: The joy of sequences

Grokking Lazy Sequences & Collections

Alex | April 18, 2016

Leave a Reply