Swift:填充二维数组时索引超出范围错误

时间:2018-12-04 16:24:48

标签: arrays swift multidimensional-array skspritenode

我刚刚开始学习Swift,我想编写几年前已经在Java和C#中创建的游戏BubbleBreaker。

为此,我想创建一个冒泡的二维数组(从SKSpriteNode派生),但是,当我尝试填充该数组时,总是在索引[处出现“索引超出范围错误”。 0] [0]。有人能帮帮我吗?

class GameScene: SKScene {
    //game settings
    private var columns = 10
    private var rows = 16
    private var bubbleWidth = 0
    private var bubbleHeight = 0

    //bubble array
    private var bubbles = [[Bubble]]()

    override func didMove(to view: SKView) {
        initializeGame()
    }

    private func initializeGame() {
        self.anchorPoint = CGPoint(x: 0, y: 0)        

        //Optimize bubble size
        bubbleWidth = Int(self.frame.width) / columns
        bubbleHeight = Int(self.frame.height) / rows

        if bubbleWidth < bubbleHeight {
            bubbleHeight = bubbleWidth
        }
        else {
            bubbleWidth = bubbleHeight
        }

        //Initialize bubble array
        for i in 0 ... columns-1 {
            for j in 0 ... rows-1 {
                let size = CGSize(width: bubbleWidth, height: bubbleHeight)
                let newBubble = Bubble(size: size)
                newBubble.position = CGPoint(x: i*bubbleWidth, y: j*bubbleHeight)

                bubbles[i][j] = newBubble // THIS IS WERE THE CODE BREAKS AT INDEX [0][0]

                self.addChild(newBubble)
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

bubbles开始为空。没有任何索引。

将循环更新为以下内容:

//Initialize bubble array
for i in 0 ..< columns {
    var innerArray = [Bubble]()
    for j in 0 ..< rows {
        let size = CGSize(width: bubbleWidth, height: bubbleHeight)
        let newBubble = Bubble(size: size)
        newBubble.position = CGPoint(x: i*bubbleWidth, y: j*bubbleHeight)

        innertArray.append(newBubble)
        self.addChild(newBubble)
    }
    bubbles.append(innerArray)
}

这将建立一个数组数组。

答案 1 :(得分:0)

不是将新值分配为不存在的值,而是为每列追加Bubble的新空数组,然后为每行追加到该数组newBubble

for i in 0 ... columns-1 {

    bubbles.append([Bubble]())

    for j in 0 ... rows-1 {

        let size = CGSize(width: bubbleWidth, height: bubbleHeight)
        let newBubble = Bubble(size: size)
        newBubble.position = CGPoint(x: i*bubbleWidth, y: j*bubbleHeight)

        bubbles[i].append(newBubble)

        self.addChild(newBubble)
    }
}