I’ve written a simple code which appends a random number inside a loop.
var randomNumber = Int.random(in: 0...3)
var array = [Int]()
for _ in 1...4 {
array.append(randomNumber)
}
print(array)
Instead of appending different numbers for each loop iteration I receive the same ones.
Debug console:
[0,0,0,0]How can I print a different number for each loop iteration?
2
Answers
maybe you should create the random number insude the loop as follow:
This is caused because the random number is created outside of the for loop and won’t change because it is created only once.
Instead create the random number inside your for loop