1

I am using this code:

    var dictionary: [Int:Int] = [:]
    var p = 1

    for _ in odds{
        if p == 1{
            dictionary[0] = 0
        }
        dictionary.updateValue(0, forKey: p)
        p += 1
        print(dictionary)
    }

I get this as output:

[0: 0, 1: 0]
[2: 0, 0: 0, 1: 0]
[2: 0, 0: 0, 1: 0, 3: 0]
[4: 0, 2: 0, 0: 0, 1: 0, 3: 0]
[4: 0, 5: 0, 2: 0, 0: 0, 1: 0, 3: 0]
[2: 0, 4: 0, 5: 0, 6: 0, 0: 0, 1: 0, 3: 0]
[2: 0, 4: 0, 5: 0, 6: 0, 7: 0, 0: 0, 1: 0, 3: 0]
[8: 0, 2: 0, 4: 0, 5: 0, 6: 0, 7: 0, 0: 0, 1: 0, 3: 0]
[8: 0, 2: 0, 4: 0, 9: 0, 5: 0, 6: 0, 7: 0, 0: 0, 1: 0, 3: 0]
[8: 0, 10: 0, 2: 0, 4: 0, 9: 0, 5: 0, 6: 0, 7: 0, 0: 0, 1: 0, 3: 0]

I want it to have [0: 0, 1: 0. 2: 0, 3: 0, etc.]

How to make this work? Thx

Hamish
  • 78,605
  • 19
  • 187
  • 280
J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • 2
    The order of key/value pairs in a dictionary is *unspecified.* – Martin R Apr 10 '17 at 18:17
  • 2
    Yes, that's to be expected, as the order of key-value pairs in a `Dictionary` is unspecified – *completely* unrelated to the order in which you add them. – Hamish Apr 10 '17 at 18:18
  • 1
    Dictionary types in Swift are not ordered. Maybe this could help? http://timekl.com/blog/2014/06/02/learning-swift-ordered-dictionaries/ –  Apr 10 '17 at 18:18
  • 3
    Possible duplicate of http://stackoverflow.com/questions/41619055/swift-dictionary-ordering, http://stackoverflow.com/questions/31722862/for-loop-for-dictionary-dont-follow-its-order-in-swift, http://stackoverflow.com/questions/31088973/dictionary-wrong-order-json – Martin R Apr 10 '17 at 18:21
  • Yes I am sorry, I did not know the right search words for it. Thanks anyway :) – J. Doe Apr 10 '17 at 19:25

1 Answers1

1

If you want to retain your logic you can sort the Dictionary as the last thing, as in:

var dictionary: [Int:Int] = [:]
var p = 1

for _ in odds{
    if p == 1{
        dictionary[0] = 0
    }
    dictionary.updateValue(0, forKey: p)
    p += 1
    print(dictionary.sorted(by: { (a, b) -> Bool in
        return a.key < b.key
    }))
}

Or refactor the code to use an array:

var array = [(key: Int, value: Int)]()
var p = 1

for _ in odds{
    array.append((key: p-1, value: 0))
    p += 1
    print(array)
}
Andre
  • 1,135
  • 9
  • 20