我想将 Doubles 的可变 3d 数组中的元素设置为三维输入函数的输出,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)
现在,其余代码将正常工作。
你可以试试这个,对于像这样声明的数组[[[Double]]]
你只能使用append,但要分配和索引它,你必须首先像这样初始化它
//Size of array: 7*7*7
let aMax = 7
let nMax = 7
let bMax = 7
//Define mutable array; I don't know if I need to initialize array "points".
var points = [[[Double]]](repeating: [[Double]](repeating: [Double](repeating: 0, count: bMax), count: nMax), count: aMax)
//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)
您可以使用Array.map(_:)
在一次镜头中声明和初始化"3D"数组:
let (aCount, nCount, bCount) = (8, 8, 8)
let points: [[[Double]]] = (0 ..< aCount).map { aInt in
let a = Double(aInt)
return (0 ..< nCount).map { nInt in
let n = Double(nInt)
return (0 ..< bCount).map { bInt in
return f(a: a, n: n, b: Double(bInt))
}
}
}