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?

1
  • 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. Commented Oct 23, 2018 at 17:27

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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)
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.