Explaining the Iterator Design Pattern in Swift

The iterator design pattern is a software design pattern in which an iterator is used to traverse a container and access the elements of the container. This pattern is used to provide a standard way to access the elements of a container without exposing the underlying representation of the container.

Here is an example of the iterator design pattern in Swift:

protocol Iterator {
    func hasNext() -> Bool
    func next() -> Any
}

protocol Collection {
    func createIterator() -> Iterator
}

class Numbers: Collection {
    private let numbers: [Int]

    init(numbers: [Int]) {
        self.numbers = numbers
    }

    func createIterator() -> Iterator {
        return NumbersIterator(numbers: numbers)
    }
}

class NumbersIterator: Iterator {
    private let numbers: [Int]
    private var index: Int = 0

    init(numbers: [Int]) {
        self.numbers = numbers
    }

    func hasNext() -> Bool {
        return index < numbers.count
    }

    func next() -> Any {
        let number = numbers[index]
        index += 1
        return number
    }
}

let numbers = Numbers(numbers: [1, 2, 3, 4, 5])
let iterator = numbers.createIterator()

while iterator.hasNext() {
    print(iterator.next())
}

// 1
// 2
// 3
// 4
// 5

In this example, the Numbers class is a container that holds a collection of numbers, and the NumbersIterator class is an iterator that can be used to traverse the Numbers container and access its elements. The Numbers class conforms to the Collection protocol and has a createIterator() method that returns a NumbersIterator instance. The NumbersIterator class conforms to the Iterator protocol and has hasNext() and next() methods that are used to traverse the Numbers container.

In this example, the Numbers class is used to create a collection of numbers, and the NumbersIterator class is used to iterate over the collection of numbers and print each number to the console. The hasNext() method is used to check if there are more numbers in the collection, and the next() method is used to access the next number in the collection.

Previous
Previous

How to create Customized and Reusable Views through Subclassing in Swift

Next
Next

Explaining the Chain of Responsibility Design Pattern