3

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?

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
grantespo
  • 2,233
  • 2
  • 24
  • 62
  • 1
    Unrelated, but you would get better clarity and performance if add an initializer to `Deque` that takes an array of initial values. This would be particularly useful, because it would allow you to initialize the `Deque` using a `map` call over those ranges. – Alexander Oct 23 '18 at 17:27

2 Answers2

4
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)
Kon
  • 4,023
  • 4
  • 24
  • 38
3

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)
    }
  }
}
Vuong Cuong
  • 192
  • 9