-1

SWIFT / IOS / Dictionary / Generator / Sequence

I have created a ordered dictionary using blogpost http://timekl.com/blog/2014/06/02/learning-swift-ordered-dictionaries/

As described in blog, I have implemented subscripts for this class to access member of the underlying dictionary.

Now to traverse the dictionary in FOR IN loop for (key, value) in orderedDict

I understand i have to write a Generator and Sequence. I also know the two protocols. From another blog, http://natashatherobot.com/swift-conform-to-sequence-protocol/ I am trying to create a generator specific to my dictionary but unable to do so. Any help in this regard will be very helpful

nkp
  • 181
  • 2
  • 12
  • Have a look at [Add “for in” support to iterate over Swift custom classes](http://stackoverflow.com/questions/24099227/add-for-in-support-to-iterate-over-swift-custom-classes). – Martin R Jul 28 '15 at 07:58

2 Answers2

1

Got the answer, you will have to add following code extending orderedDictionary with SequenceType and adding a Generate method

/// extension class

extension OrderedDictionary: SequenceType {

    /// Creates a generator for each (key, value)
    func generate() -> GeneratorOf<(Tk , Tv)> {
        var index = 0
        return GeneratorOf<(Tk , Tv)> {
            if index < self.count {
                let key = self.keys[index]
                let value = self[index]
                index++
                return (key, value!)
            } else {
                index = 0
                return nil
            }
        }
    }
}
nkp
  • 181
  • 2
  • 12
0

I found another ordered dictionary on https://github.com/Marxon13/M13DataStructures/blob/master/Classes/OrderedDictionary.swift

And I used the entries var from that example which returns an array so we can use the array generator:

struct ADOrderedDictionary<Tk: Hashable, Tv:Equatable>:SequenceType
(etc.)

    var entries:Array<(Tk, Tv)> {
    get {
        var tempArray:Array<(Tk, Tv)> = []
        for key: Tk in keys {
            let value = values[key]!
            tempArray.append(key, value)
        }
        return tempArray
    }
}

func generate() -> IndexingGenerator<[(Tk,Tv)]>
{
    return self.entries.generate()
}

This allows "for (key, value) in orderedDictionary"

Dan Selig
  • 234
  • 2
  • 11