arraysswiftswift-playgroundswift-structs

Swift - Dynamic Array of Struct


I have a struct:

public struct Deque<T> {

    private var array = [T]()

    public var isEmpty: Bool {
        return array.isEmpty
    }

    public var count: Int {
        return array.count
    }

    public mutating func enqueue(_ element: T) { //inserts element at end
        array.append(element)
    }

    public mutating func enqueueFront(_ element: T) { //inserts element at beginning
        array.insert(element, at: 0)
    }
}

And I declare the struct like this:

var burst = [Deque<Int>()]

And I initialize it like this in a for loop:

for i in 0..<9 {
    for j in 0..<10{
    if processes[i][j] != 0{
        burst[i].enqueue(processes[i][j])
    }
  }
}

I am able to initialize index 0 of my struct successfully, however, whenever i get to index 1, I get an error:

Fatal error: Index out of range

How do I declare and initialize a dynamic array of structs in swift?


Solution

  • var burst = [Deque<Int>()]
    

    This declares burst to be an array of 1 Deque object. You're trying to access burst[i] where i is greater than 0, which is outside of burst range.

    You can use Array init(repeating:count:) initializer (doc) like so:

    var burst = Array<Deque<Int>>(repeating: Dequeue<Int>(), count: 10)