skip to Main Content

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


  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)
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search