concept BagIterator in category swift

appears as: BagIterator, BagIterator
Swift in Depth

This is an excerpt from Manning's book Swift in Depth.

9.3.2. Creating a BagIterator

You can already use Bag as is. But you can’t iterate over it until you implement Sequence. To implement Sequence, you need an iterator, which you’ll creatively call BagIterator.

You need to apply a little trick because Bag is lying. It isn’t holding the number of elements that it says it does; it’s merely holding the element with a counter. So you’ll apply a trick: BagIterator returns the same element a multiple of times depending on the element’s count. This way, an outsider doesn’t need to know about the tricks Bag uses, and yet it gets the correct amount of elements.

Every time you call next on BagIterator, the iterator returns an element and lowers its count. Once the count hits nil, BagIterator removes the element. If no elements are left, the iterator is depleted and returns nil, signaling that BagIterator has finished iteration. The following listing gives an example of this.

Listing 9.18. Creating a BagIterator
struct BagIterator<Element: Hashable>: IteratorProtocol {        #1
 
    var store = [Element: Int]()                                 #2
 
    mutating func next() -> Element? {                           #3
         guard let (key, value) = store.first else {             #4
             return nil                                          #4
         }
         if value > 1 {                                          #5
             store[key]? -= 1                                    #5
         } else {
             store[key] = nil                                    #6
         }
         return key                                              #7
     }
}

You’re almost there. With BagIterator in place, you can extend Bag and make it conform to Sequence, as shown in the following listing. All that you need to do is implement makeIterator and return a freshly made BagIterator, which gets a fresh copy of store.