gpt4 book ai didi

arrays - Swift 追加到二维数组

转载 作者:行者123 更新时间:2023-11-28 10:50:29 24 4
gpt4 key购买 nike

我试图在 Swift 中将一个值附加到二维数组,但它在第 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)
}
}
}

Swift code

最佳答案

您不能使用 cards[0] 访问 cards 的内部数组,因为您将 cards 初始化为空数组,因此cards.count = 0,所以 cards[0] 不存在。

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])
}
}
}

关于arrays - Swift 追加到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46315666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com