-3

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?

leopoldubz
  • 39
  • 4

2 Answers2

1

maybe you should create the random number insude the loop as follow:

var array = [Int]()

for _ in 1...4 {
    array.append(Int.random(in: 0...3))
}

print(array)
oded bartov
  • 391
  • 1
  • 2
  • 9
1

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

var array = [Int]()

for _ in 1...4 {
    let randomNumber = Int.random(0...3)
    array.append(randomNumber)
}

print(array)
adam eliezerov
  • 2,185
  • 2
  • 11
  • 17