Swift Sequences

Swift Sequences

I’ve had a lot of fun around the Swift APIs over the past few weeks. I have found there are lot more real gems hidden among the more unremarkable API and language features.

In this blog post I want to have a quick look at the Swift Sequence protocol, which forms the basis for-in loop, and see how this allows us to write code that performs & evaluated on-demand sequence operations.

Swift has a couple of very beautiful language features, the for-in loop and ranges, that when used in combination provide a very short syntax for simple loops:

for i in 1...5 {

The above code iterates over the integers in the range 1 through to 5.


for i in 1..<5 {

The above code iterates over the integers in the range 1 through to 4.

The funky range operator (…) & (..<) is a simple shorthand for creating Range instances. As a result, the following code is entirely equivalent:

var range = Range(start: 1, end: 5)
for i in range {

However the most important thought is, what is it about Range that allows the for-in loops to iterate over the numbers is generates?

The for-in loop operates on objects that adopt the Sequence protocol, which represents an ordered source of data.

The Sequence protocol exposes a single method, generate(), which returns a Generator, which exposes a single method next() which allows the for-in loop to ‘pull’ a stream of items from the sequence.

This will probably all make a lot more sense by continuing to expand the current example to make explicit use of the sequence’s generator:

var sequence = Range(start: 1, end: 5)
var generator = sequence.generate()
while let i = generator.next() {

One interesting point is that the Swift Range is a finite sequence, in that it has a start and an end. The Sequence protocol does not mandate this, and can be used to represent infinite sequences (although we should probable avoid using infinite sequences with for-in loops!)


Swift sequences are really cool and with a lot of potential. The examples in this blog post have been a little contrived, However, I could certainly see myself operating on sequences generated from streams.

Leave a Reply

Your email address will not be published. Required fields are marked *