向字典添加值不正确

时间:2017-04-10 18:15:08

标签: swift

我正在使用此代码:

    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

1 个答案:

答案 0 :(得分: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)
}