简体   繁体   English

Swift - 动态结构数组

[英]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循环中将它初始化为:

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: 我能够成功初始化我的struct的索引0,但是,每当我到索引1时,我都会收到错误:

Fatal error: Index out of range 致命错误:索引超出范围

How do I declare and initialize a dynamic array of structs in swift? 如何在swift中声明和初始化动态结构数组?

var burst = [Deque<Int>()]

This declares burst to be an array of 1 Deque object. 这声明burst是一个1 Deque对象的数组。 You're trying to access burst[i] where i is greater than 0, which is outside of burst range. 您正在尝试访问其中i大于0的burst[i] ,这超出了burst范围。

You can use Array init(repeating:count:) initializer ( doc ) like so: 您可以使用Array init(repeating:count:)初始化程序( doc ),如下所示:

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: 您正在使用此命令在“burst”数组中仅创建一个“Deque”类型的元素:

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. 这就是为什么当你尝试访问i> 0的“burst”数组时,它会崩溃。 You need to init a new Deque object before appending to the array, then call 您需要在追加到数组之前初始化一个新的Deque对象,然后调用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM