【问题标题】:Swift: Index Out of Range Error when Populating Two-Dimensional ArraySwift:填充二维数组时出现索引超出范围错误
【发布时间】:2018-12-04 16:24:48
【问题描述】:

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

为此,我想创建一个 Bubble 的二维数组(从 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)
            }
        }
    }
}

【问题讨论】:

  • 下面的答案为您指明了正确的方向,但关键是在 Swift 的标准库中没有“二维数组”之类的东西。 [[Bubble]] 是一个数组数组。那不是一回事(每个“行”可以是不同的长度)。如果您需要一个真正的二维数组(矩阵),那么您将需要一个专门的类型。有关 Matrix 类型的示例,请参阅 stackoverflow.com/a/53421491/97337

标签: arrays swift multidimensional-array skspritenode


【解决方案1】:

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

这构建了一个数组数组。

【讨论】:

    【解决方案2】:

    不要将新值分配为不存在的值,而是为每一列追加新的空数组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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多