Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Sequence & IteratorProtocol Protocols in Swift
Written by Team Kodeco

The Sequence protocol in Swift is a fundamental protocol that provides a blueprint for objects that represent a sequence of values. It requires the implementation of a single method, makeIterator(), which returns an instance of Iterator, a protocol that defines the behavior of iterating over the values in the sequence.

The Sequence protocol allows sequences to be used in many Swift Standard Library functions, such as map, filter, reduce and sorted, that operate on sequences and make it easy to work with collections of values. By conforming to the Sequence protocol, custom classes and structs can participate in the same rich set of operations as built-in sequences, such as arrays and ranges.

Here’s an example:

struct Ints: Sequence {
  let start: Int
  let end: Int

  func makeIterator() -> IntIterator {
    return IntIterator(start: start, end: end)
  }
}

struct IntIterator: IteratorProtocol {
  let end: Int
  var current: Int

  init(start: Int, end: Int) {
    self.end = end
    self.current = start
  }

  mutating func next() -> Int? {
    if current < end {
      let value = current
      current += 1
      return value
    }
    return nil
  }
}

This example defines a Sequence named Ints which generates a sequence of integers. The Ints type implements the Sequence protocol by providing an IntIterator to iterate over the values in the sequence. The IntIterator type implements the IteratorProtocol protocol, which defines the next method to return the next value in the sequence or nil when the end of the sequence is reached.

You can then use this Ints type like this:

for i in Ints(start: 0, end: 3) {
  print(i)
}
// Prints: 0
//         1
//         2

This demonstrates how the Ints type can be used like an array or any other sequence, by using a for-in loop to iterate over its values.

© 2024 Kodeco Inc.