swift - 向字典中添加值不正确

标签 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, etc.]

如何实现?谢谢

最佳答案

如果您想保留您的逻辑,您可以将 Dictionary 排序为最后一件事,如:

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

关于swift - 向字典中添加值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330166/

相关文章:

ios - 来自 Apple 网站的日期示例代码不起作用?

ios - 将 Int16 类型的整数保存到 Core Data - Swift

ios - 我怎样才能移动到另一个 View Controller ?

ios - 基于 UIScrollView 内容 View 高度不增加

ios - 调整单元格大小以适合标签,已设置图像大小并且标签有一些圆角

swift - 使用 AnyObject 时 Bool 被视为 int

ios - 位图 CGContext 绘图不断增加内存使用量

ios - 将图像转换为黑白同时保留 alpha channel

swift - AWS APIGatewayClient(Swift) 在 Swift3 中不起作用?

ios - View 在 iPhone X 横向模式下看起来不正确