Swift - Dynamic Array of Struct

Viewed 1379

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?

2 Answers
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)

You are creating only one element of type "Deque" in the "burst" array with this command:

var burst = [Deque<Int>()]  //There is only one element inside the array

That's why when you try to access the "burst" array with i > 0, it crashes. You need to init a new Deque object before appending to the array, then call

burst[i]

later

You can do it this way:

for i in 0..<9 {
  for j in 0..<10{
    if processes[i][j] != 0{
        var queue = Deque<Int>()
        queue.enqueue(processes[i][j])
        burst.append(queue)
    }
  }
}
Related