The issue is that Int(arc4random())%windCard.count
generates keys in the range 0
to windCard.count-1
, while your keys start from 1 and after you remove the first element, the keys won't even be contiguous. So for instance if you remove a key from the middle of your Dictionary
(let's say key 5
), windCard
will have 9 elements and hence die
will be in the range 0-8
, but your Dictionary
will be missing a key, so your code will crash on windCard[key]!
if die
is 5
.
You can achieve your goal by using arc4random_uniform
, which accepts an upperBound
input argument and using the generated random number to subscript the keys
of your windCard
Dictionary
, which will guaranteed to be contiguous.
while windCard.count > 0 {
let die = Int(arc4random_uniform(UInt32(windCard.keys.count)))
let key = Array(windCard.keys)[die]
print("The wind blow the mosquitoes \(windCard[key]!)")
windCard.removeValue(forKey: key)
}