用循环填充多维数组 [英] Populate a multidimensional array with a loop
问题描述
$ $ $ $ $ $ $ var array = [[Int]]()
for i in 0 ... 3 {
for j in 0 ... 3 {
array [i] [j] = i + j << - 错误
}
}
但是我得到一个错误:
$ b $
致命错误:索引超出范围
我在做什么错了?
调用数组[i] [j ]
是已经存在的元素。你不能用它来初始化数组,因为目前它只是一个空数组。您应该使用 .append
来代替。请记住,这实际上并不像罗布·纳皮尔(Rob Napier)所说的那样是一个多维数组,但是它在这种情况下完成了相同的目标。试试像这样:
var array = [[Int]]()
for i in 0 ... 3 {
var subArray = [Int]()
for j in 0 ... 3 {
subArray.append(i + j)
}
array.append(subArray)
}
/ b>
<[0,1,2,3],[1,2,3,4],[2,3,4,5 ],[3,4,5,6]]
再次,可能不是最好的方法,但这只是你可以在Swift中完成。
I'm trying to populate a multidimensional array with this code:
var array = [[Int]]()
for i in 0...3 {
for j in 0...3{
array[i][j] = i + j <<- Error
}
}
But I get an error:
fatal error: Index out of range
What am I doing wrong?
Calling array[i][j]
is for elements that are already there. You cannot use it to initialize the array, because currently it is just an empty array. You should be using .append
instead. Keep in mind that this actually isn't a multi-dimensional array like Rob Napier states, but it accomplishes the same goal in this scenario. Try something like this:
var array = [[Int]]()
for i in 0...3 {
var subArray = [Int]()
for j in 0...3 {
subArray.append(i + j)
}
array.append(subArray)
}
This prints:
[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
Again, may not be the best approach, but this is just how you could do it in Swift.
这篇关于用循环填充多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!