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:
- A generator class for a defined number of iterations
- Using AnyGenerator for a bounded number of iterations
- 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:
And what do you get when you add indexability to a sequence? Why, a collection:
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: