我想将可变 3d double 组中的元素设置为 3 输入函数 f()
的输出,用于数组中该元素的位置( [a][n][b]
),然后打印数组。
//3-input function must input and output doubles. This function is an example.
func f(a: Double, n: Double, b: Double) -> Double {
return a * n * b
}
//Size of array: 7*7*7
let aMax = 6
let nMax = 6
let bMax = 6
//Define mutable array; I don't know if I need to initialize array "points".
var points = [[[Double]]]()
//I don't know if I should use ".append" or "=".
for a in 0...aMax {
for n in 0...nMax {
for b in 0...bMax {
points[a][n][b] = f(a: Double(a), n: Double(n), b: Double(b)) //Changing element at position results in "fatal error: Index out of range".
}
}
}
print(points)
最佳答案
问题是在做了之后:
var points = [[[Double]]]()
points
完全是空的。因此,任何访问任何索引的尝试都会导致“索引超出范围”错误。
因为你要填充整个东西,所以使用 Array(repeating:count:)
初始化三个维度。
var points = Array(repeating: Array(repeating: Array(repeating: 0.0, count: bMax + 1), count: nMax + 1), count: aMax + 1)
现在您的其余代码可以工作了。
关于arrays - 索引超出范围 : Mapping the output of a 3-input function to a 3-dimentional floating-point array in Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51181482/