Fatal error: Index out of range. In for loop using an array.

Hi.
I have a problem. When I try to generate random numbers from 1 to 4 to an array I get a fatal error "Thread 1: Fatal error: Index out of range" and everything crashes.

Here is my code:
Code Block
import Foundation
let maxLevel:Int = 99
var randomSeq: [Int] = []
struct NumGen{
    static func Generate() -> Void {
        for i in 1...maxLevel{
            randomSeq[i] = Int.random(in: 1...4)
            print(i)
        }
    }
}

BTW I am using m1 mac mini if that makes a difirence.

Plese help. Thanks
Answered by OOPer in 674701022
With this line:
Code Block
var randomSeq: [Int] = []

You initialize randomSeq with a zero-length Array.
So, any index including 0 would cause Index out of range.

In Swift, accessing an Array with subscript does not automatically extend the Array, and may cause Index out of range.

I guess, you may need to write something like this:
Code Block
import Foundation
let maxLevel: Int = 99
var randomSeq: [Int] = []
struct NumGen {
static func generate() {
//randomSeq.removeAll()
for i in 1...maxLevel {
randomSeq.append(Int.random(in: 1...4))
print(i)
}
}
}


Accepted Answer
With this line:
Code Block
var randomSeq: [Int] = []

You initialize randomSeq with a zero-length Array.
So, any index including 0 would cause Index out of range.

In Swift, accessing an Array with subscript does not automatically extend the Array, and may cause Index out of range.

I guess, you may need to write something like this:
Code Block
import Foundation
let maxLevel: Int = 99
var randomSeq: [Int] = []
struct NumGen {
static func generate() {
//randomSeq.removeAll()
for i in 1...maxLevel {
randomSeq.append(Int.random(in: 1...4))
print(i)
}
}
}


You can also create the array with the right number of elements :

Code Block
let maxLevel:Int = 99
var randomSeq: [Int] = Array(repeating: 0, count: 99). // Array full of zero ; in playground, you can use maxLevel here

Now, you can use your code
Take care in your loop, array indexes start at zero:
Code Block
for i in 0...maxLevel-1 {
randomSeq[i] = Int.random(in: 1...4)
or
Code Block
for i in 0...randomSeq.count-1 {
randomSeq[i] = Int.random(in: 1...4)

Fatal error: Index out of range. In for loop using an array.
 
 
Q