Friday, November 6, 2026
HomeiOS DevelopmentIterator design sample in Swift

Iterator design sample in Swift

[ad_1]

Study the iterator design sample through the use of some customized sequences, conforming to the IteratorProtocol from the Swift customary library.

Design patterns

This time I’ll give attention to the iterator design sample. The sample is closely used within the Swift customary library, there are protocols that provides you with help if you’ll want to create an iterator, however truthfully: I’ve by no means carried out this sample straight. 😅

The reality is that in all probability in 99% of the use instances you may by no means must cope with this sample, as a result of there may be wonderful help for iterators built-in straight into Swift. All the time use sequences, arrays, dictionaries as an alternative of straight implementing this sample, nevertheless it’s good to know the way issues are working below the hood, is not it? 🙃


What’s the iterator desin sample?

Because the title suggests, the sample lets you iterate over a set of parts. Right here is the definition from the gang of 4 ebook:

Present a approach to entry the weather of an mixture object sequentially with out exposing its underlying illustration.

Lengthy story brief the iterator provides you an interface that may allow you to iterate over collections no matter how they’re carried out within the background. Here’s a fast instance of the idea above utilizing a string iterator.

import Basis

protocol StringIterator {
    func subsequent() -> String?
}

class ArrayStringIterator: StringIterator {

    non-public let values: [String]
    non-public var index: Int?

    init(_ values: [String]) {
        self.values = values
    }

    non-public func nextIndex(for index: Int?) -> Int? {
        if let index = index, index < self.values.depend - 1 {
            return index + 1
        }
        if index == nil, !self.values.isEmpty {
            return 0
        }
        return nil
    }

    func subsequent() -> String? {
        if let index = self.nextIndex(for: self.index) {
            self.index = index
            return self.values[index]
        }
        return nil
    }
}


protocol Iterable {
    func makeIterator() -> StringIterator
}

class DataArray: Iterable {

    non-public var dataSource: [String]

    init() {
        self.dataSource = ["🐶", "🐔", "🐵", "🦁", "🐯", "🐭", "🐱", "🐮", "🐷"]
    }

    func makeIterator() -> StringIterator {
        return ArrayStringIterator(self.dataSource)
    }
}

let information = DataArray()
let iterator = information.makeIterator()

whereas let subsequent = iterator.subsequent() {
    print(subsequent)
}

As you may see there are two essential protocols and a extremely easy implementation for each of them. Our DataArray class now acts like an actual array, the underlying parts could be iterated by utilizing a loop. Let’s ditch the idea and re-implement the instance from above through the use of actual Swift customary library elements. 😉


Customized sequences in Swift

Swift has a built-in sequence protocol that can assist you creating iterators. Implementing your individual sequence in Swift is all about hiding your underlying information construction by making a customized iterator object. You simply must retailer the present index and return your subsequent factor based on that every time the subsequent perform will get referred to as. 😛

import Basis

struct Emojis: Sequence {
    let animals: [String]

    func makeIterator() -> EmojiIterator {
        return EmojiIterator(self.animals)
    }
}

struct EmojiIterator: IteratorProtocol {

    non-public let values: [String]
    non-public var index: Int?

    init(_ values: [String]) {
        self.values = values
    }

    non-public func nextIndex(for index: Int?) -> Int? {
        if let index = index, index < self.values.depend - 1 {
            return index + 1
        }
        if index == nil, !self.values.isEmpty {
            return 0
        }
        return nil
    }

    mutating func subsequent() -> String? {
        if let index = self.nextIndex(for: self.index) {
            self.index = index
            return self.values[index]
        }
        return nil
    }
}

let emojis = Emojis(animals: ["🐶", "🐔", "🐵", "🦁", "🐯", "🐭", "🐱", "🐮", "🐷"])
for emoji in emojis {
    print(emoji)
}

So the Sequence protocol is a generic counterpart of our customized iterable protocol used within the first instance. The IteratorProtocol is considerably just like the string iterator protocol used earlier than, however extra Swiftish and naturally extra generic.

So, that is nice. Lastly you understand how to create a customized sequence. Which is nice if you would like to cover your information construction and supply a generic iterable interface. Think about what would occur for those who have been about to start out utilizing a dictionary as an alternative of an array for storing named emojis with out an iterator that wraps them. 🤔

Now the factor is that there’s yet one more tremendous helpful factor within the Swift customary library that I would like to speak about. That is proper, one abstraction degree up and right here we’re:


Customized collections in Swift

Collections are one step past sequences. Components within them could be accessed by way of subscript additionally they outline each a startIndex and an endIndex, plus particular person parts of a set could be accessed a number of occasions. Sounds good? 👍

Generally it may be helpful to create a customized assortment kind. For instance if you would like to remove optionally available values. Think about a categorized favourite mechanism, for each class you’d have an array of favorites, so that you’d must cope with empty and non-existing instances. With a customized assortment you could possibly cover that additional code inside your customized information construction and supply a clear interface for the remainder of your app. 😍

class Favorites {

    typealias FavoriteType = [String: [String]]

    non-public(set) var record: FavoriteType

    public static let shared = Favorites()

    non-public init() {
        self.record = FavoriteType()
    }
}


extension Favorites: Assortment {

    typealias Index = FavoriteType.Index
    typealias Aspect = FavoriteType.Aspect

    var startIndex: Index {
        return self.record.startIndex
    }
    var endIndex: Index {
        return self.record.endIndex
    }

    subscript(index: Index) -> Iterator.Aspect {
        return self.record[index]
    }

    func index(after i: Index) -> Index {
        return self.record.index(after: i)
    }
}

extension Favorites {

    subscript(index: String) -> [String] {
        return self.record[index] ?? []
    }

    func add(_ worth: String, class: String) {
        if var values = self.record[category] {
            guard !values.accommodates(worth) else {
                return
            }
            values.append(worth)
            self.record[category] = values
        }
        else {
            self.record[category] = [value]
        }
    }

    func take away(_ worth: String, class: String) {
        guard var values = self.record[category] else {
            return
        }
        values = values.filter { $0 == worth }

        if values.isEmpty {
            self.record.removeValue(forKey: class)
        }
        else {
            self.record[category] = values
        }
    }
}


Favorites.shared.add("apple", class: "fruits")
Favorites.shared.add("pear", class: "fruits")
Favorites.shared.add("apple", class: "fruits")

Favorites.shared["fruits"]

Favorites.shared.take away("apple", class: "fruits")
Favorites.shared.take away("pear", class: "fruits")
Favorites.shared.record

I do know, it is a actually dumb instance, nevertheless it demonstrates why collections are extra superior in comparison with pure sequences. Additionally within the hyperlinks under there are nice demos of nicely written collections. Be at liberty to be taught extra about these tremendous protocols and customized information varieties hidden (not so deep) contained in the Swift customary library. 🤐

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments