【问题标题】:Adding values to dictionary does not go correctly向字典中添加值不正确
【发布时间】:2017-04-10 18:15:07
【问题描述】:

我正在使用此代码:

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

如何做到这一点?谢谢

【问题讨论】:

标签: swift


【解决方案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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    相关资源
    最近更新 更多