我正在使用这段代码:
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/