From the course: Practical Design Patterns in Swift

Sequential access - Swift Tutorial

From the course: Practical Design Patterns in Swift

Start my 1-month free trial

Sequential access

- [Instructor] Whenever you use the foreign loop to traverse over the elements of a collection, you're relying on the iterator design pattern. By definition, the iterator provides sequential access to the elements of an aggregate object. The internal structure of the traverse object is not exposed to the clients. We already know how to iterate over the elements of an array. But how about stepping through the elements of a custom link list or stack? We should be able to provide the same seamless experience as we've got for the built-in Swift collection types. The iterator provides a standard solution that can be applied to every type whether it's a foundation type or we implemented it from scratch. Instead of adding the traversal logic to the data structure itself, the iterator works by extracting this functionality into a separate type. Thus, it removes this responsibility from the collection type. Besides, we don't need to expose the details of the underlying data structure to iterate through its elements. The Swift standard library exposes two protocols that let us implement the iterator pattern, the Sequence and the IteratorProtocol. We're going to take a closer look at these protocols in the upcoming demo. The iterator pattern has no drawbacks. It is so ubiquitous that we can't avoid it. However, a sloppy iterator might affect the entire system. You should always consider the performance impact of your iterator implementation.

Contents