Chapter 13: Iterator Pattern

大綱

When should you use it?

  • The iterator pattern is a behavioral pattern that provides a standard way to loop through a collection

    • The Swift IterableProtocol: defines a type that can be iterated using a for in loop.

    • A custom object: an object you want to make iterable.

  • Instead of conforming to Iterable directly, however, you can conform to Sequence, which itself conforms to Iterable.

  • When should you use it?

    • Use the iterator pattern when you have a class or struct that holds a group of ordered objects, and you want to make it iterable using a for in loop.

Playground example

  • 目標:

  • creating a queue

  • Custom object

  • Conforming the Sequence protocol

    • The first is your associated type, which is your Iterator. In the code above, IndexingIterator is your associated type, which is the default iterator for any collection that doesn’t declare its own.

    • The second part is the Iterator protocol, which is the required makeIterator function. It constructs an iterator for your class or struct

What should you be careful about?

  • it’s almost always better to conform to Sequence and provide custom next() logic, instead of conforming to IteratorProtocol directly.

Tutorial project

Key points

  • The iterator pattern provides a standard way to loop through a collection using a for in syntax.

  • It’s better to make your custom objects conform to Sequence, instead of IteratorProtocol directly.

  • By conforming to Sequence, you will get higher-order functions like map and filter for free.

Last updated