gpt4 book ai didi

arrays - 如何在 swift 4 中声明数组索引的类型

转载 作者:行者123 更新时间:2023-11-28 14:53:06 25 4
gpt4 key购买 nike

我正在尝试创建一个 2D 查找表,其中包含代表 swift 4 中表轴的枚举,例如:

enum ECT: Int {
case cool = 0
case normal
case above_range
}

enum Load: Int {
case idle = 0
case cruise
case wot
}

var timingRetard = [[Double?]](repeating: [nil,nil,nil], count 3)

(不,我不是在 Swift 中编写嵌入式 PCM 代码(虽然那会很有趣!),但它是我尝试使用但尚未弄清楚语法的 swift 构造的一个简单示例)

如何使用枚举作为索引在数组中分配和检索值,例如假设元素已经创建

timingRetard[cool][idle] = 0.0
timingRetard[cool][cruise] = 0.0
timingRetard[cool][wot] = 0.0
timingRetard[above_range][wot] = -8.0
timingRetard[normal][cruise] = 0.0

在给定每个轴的枚举数量的情况下,如何在初始化数组后声明仅由枚举类型访问的 Swift 数组的索引类型?我想我可以将 timingRetard 添加到结构并声明一个下标方法来将索引限制为枚举类型,但也没有让它起作用。

最佳答案

实现的一种方法是覆盖结构中的下标方法。解释得更好here .我使用链接中提到的示例以这种方式解决了您的问题:

enum ECT: Int{
case cool = 0
case normal
case above_range
}

enum Load: Int {
case idle = 0
case cruise
case wot
}

struct TimingRetard2D {
let rows: Int, cols: Int
private(set) var array:[Double?]

init(rows: Int, cols: Int, repeating:Double?) {
self.rows = rows
self.cols = cols
array = Array(repeating: repeating, count: rows * cols)
}

private func indexIsValid(row: Int, col: Int) -> Bool {
return row >= 0 && row < rows && col >= 0 && col < cols
}

subscript(row: ECT, col: Load) -> Double? {
get {
assert(indexIsValid(row: row.rawValue, col: col.rawValue), "Index out of range")
return array[(row.rawValue * cols) + col.rawValue]
}
set {
assert(indexIsValid(row: row.rawValue, col: col.rawValue), "Index out of range")
array[(row.rawValue * cols) + col.rawValue] = newValue
}
}
}

var timingRetard = TimingRetard2D.init(rows: 3, cols: 3, repeating: nil)
timingRetard[.cool, .idle] = 0.0
timingRetard[.cool, .cruise] = 0.0
timingRetard[.cool, .wot] = 0.0
timingRetard[.above_range, .wot] = -8.0
timingRetard[.normal, .cruise] = 0.0
print(timingRetard.array)

输出:

[可选(0.0), 可选(0.0), 可选(0.0), nil, 可选(0.0), nil, nil, nil, 可选(-8.0)]

关于arrays - 如何在 swift 4 中声明数组索引的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49642266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com