快速附加到2D数组 [英] Swift append to 2d array
本文介绍了快速附加到2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Swift中将一个值附加到2d数组中,但在第8行上却抛出了索引超出范围"错误
I'm trying to append a value to a 2d array in Swift but it's throwing me an "index out of range" error on line 8
private var cards : [[Int]] = [[]]
init() {
//Fill cards array by adding all cards
for i in 0...12{
for x in 0...3{
cards[0].append(i+2) //append card number... 2,3,4,5 etc
cards[1].append(x) //append card type... hearts, diamonds, clubs and spades
//with a value which represents it (0, 1, 2 and 3)
}
}
}
推荐答案
由于初始化了 cards [0]
访问 cards
的内部数组> cards 作为数组的空数组,因此 cards.count = 0
,因此 cards [0]
不存在.
You cannot access the inner arrays of cards
using cards[0]
, since you initialize cards
as an empty array of arrays and hence cards.count = 0
, so cards[0]
does not exist.
private var cards = [[Int]]()
init() {
//Fill cards array by adding all cards
for i in 0...12{
for x in 0...3{
cards.append([i+2,x])
}
}
}
这篇关于快速附加到2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文