Ghost108 Ghost108 - 3 years ago 131
Swift Question

Dictionary key count has wrong result

I'm working with Swift 4 for macOS and I have a problem with my for each loop.

My code:

var dict = [String:Int]()

for x in 0 ..< 5 {
if !dict.keys.contains("\(x)") {
print("NEW KEY: \(x)")
dict = ["\(x)" : x]
}
}

print(dict.keys.count)


My print results:

NEW KEY: 0
NEW KEY: 1
NEW KEY: 2
NEW KEY: 3
NEW KEY: 4
1


But why is
keys.count = 1
?

Answer Source

You are overwriting the dictionary with each iteration of the for loop.

Replace

dict = ["\(x)" : x]

with

dict["\(x)"] = x
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download