Over a million developers have joined DZone.

Swift Sequences: The .next() Generator

A quick introduction to some of the Swift libraries for handling sequences and generators.

· Mobile Zone

Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud, brought to you in partnership with IBM.

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

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:

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:

The Mobile Zone is brought to you in partnership with Strongloop and IBM.  Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud.


Published at DZone with permission of Alex Curylo, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}