arrays - Swift - 动态结构数组

标签 arrays swift swift-playground swift-structs

我有一个结构:

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

然后我这样声明结构:

var burst = [Deque<Int>()]

然后我在 for 循环中像这样初始化它:

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

我能够成功初始化我的结构的索引 0,但是,每当我到达索引 1 时,我都会收到错误消息:

Fatal error: Index out of range

如何在 swift 中声明和初始化结构的动态数组?

最佳答案

var burst = [Deque<Int>()]

这将 burst 声明为 1 Deque 对象的数组。您正在尝试访问 burst[i],其中 i 大于 0,这在 burst 范围之外。

您可以像这样使用数组 init(repeating:count:) 初始化器 ( doc ):

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

关于arrays - Swift - 动态结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52953973/

相关文章:

c - 指针和字符数组

java迷宫游戏错误仅朝一个方向进行,使用数组

ios - 如何将自己的项目中的类导入到 Playground 中

xcode - 二元运算符 '/' 不能应用于两个 (Int) 操作数

ios - 在 UISplitViewController 中,如何让 master 打开 iPhone 的详细 View Controller ?

Swift – Balloons.playground – 无法将 "textures"添加到时间轴

C++ 堆栈和二维数组

javascript - 在 JavaScript 中从数组中查找索引#

ios - 不能快速在不同大小的类型之间使用 unsafeBitCast

Swift - 长按按钮上的手势以使用 AVFoundation 录制音频