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:
BTW I am using m1 mac mini if that makes a difirence.
Plese help. Thanks
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
With this line:
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 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) } } }