2017-04-10 57 views
1

我使用這個代碼:增加值字典不走正確

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) 
    } 

我得到這個作爲輸出:

[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] 

我希望它有[0:0,1:0 。2:0,3:0等]

如何使這項工作? THX

+2

的順序字典中的鍵/值對是未指定的* –

+2

是的,這是可以預料到的,因爲「字典」中的鍵值對的順序未指定 - *完全*與您添加它們的順序無關。 – Hamish

+1

Swift中的字典類型未被排序。也許這可能有幫助? http://timekl.com/blog/2014/06/02/learning-swift-ordered-dictionaries/ – dfd

回答

1

如果你想留住你的邏輯,你可以在詞典排序的最後一件事,如:

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 
    })) 
} 

或者重構代碼使用數組:

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

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