The code crashes after 3 tries. How do I manage to print all 10 values without repeating them?
var windCard = [1:11, 2:12, 3:21, 4:22, 5:31, 6:32, 7:41, 8:42, 9:51, 10:52 ]
var die = 0
die = Int(arc4random())%windCard.count
print("The wind blow the mosquitoes \(windCard[Int(die)]!)")
windCard.removeValue(forKey: die)
The issue is that
Int(arc4random())%windCard.countgenerates keys in the range0towindCard.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 yourDictionary(let's say key5),windCardwill have 9 elements and hencediewill be in the range0-8, but yourDictionarywill be missing a key, so your code will crash onwindCard[key]!ifdieis5.You can achieve your goal by using
arc4random_uniform, which accepts anupperBoundinput argument and using the generated random number to subscript thekeysof yourwindCardDictionary, which will guaranteed to be contiguous.