From the course: Practical Design Patterns in Swift

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Adding for-in loop support to the queue

Adding for-in loop support to the queue - Swift Tutorial

From the course: Practical Design Patterns in Swift

Start my 1-month free trial

Adding for-in loop support to the queue

- [Instructor] Let's add support for iterating through the queue's elements, using a for-in loop. We're going to implement the iterator pattern the Swift way. The Swift standard library exposes two protocols that let us implement the iterator pattern, Sequence and the Iterator protocol. By adding Sequence protocol conformance to our queue, we can create the custom iterator that provides sequential access to its elements. The Iterator protocol should be adopted by the iterator type. We start with the Sequence protocol conformance. I'm going to adopt the Sequence protocol in an extension, to avoid cluttering the implementation of the Queue class. So, let's provide an extension for the Queue class that conforms to the Sequence protocol. And we need to define the makeIterator method. MakeIterator must return an iterator. So, we'll create a dedicated type called QueueIterator. It's a generic type, and will return QueueIterator{self}. Now, the type is obviously missing, so let's create it…

Contents