arrays - 索引超出范围 : Mapping the output of a 3-input function to a 3-dimentional floating-point array in Swift 4

标签 arrays swift multidimensional-array indexoutofboundsexception indexoutofrangeexception

我想将可变 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/

相关文章:

java - 如何从二维对象数组中获取数据?

swift - 在 Firebase 中一段时间​​后更改值

swift - 错误类型 'MyClass"在 "onTimer' 上没有成员

php - Swift SHA256 哈希与 PHP SHA256 哈希不匹配

php - 如何在不使用foreach方法的情况下将多维数组转换为一维数组

arrays - 在多维数组上一起使用 `flatMap().filter().map()`

PHP多重循环生成新数组

javascript - 找到最相似的数字数组

java - 根据 Collection.toArray(T[] array) 合约将 Java 流转换为数组

Javascript矩阵数组问题