'How to divide screen into a grid using 2d arrays in swift?

Below is my code so far using for loops, and this is what it looks like right now. As you can see it is very condensedthis

         for i in 0...12{
            for j in 0...16{
                
            let block = SKSpriteNode(texture: blockImage, size: blockSize)
                block.position.x = block.frame.width/2 * CGFloat(j)+1
                block.position.y = frame.height - block.frame.height/2 * CGFloat(i)+1
                block.zPosition = 1
                
                
                addChild(block)
        }
        }

However, I am only trying to have 2 rows of blocks on the top and 1 row of blocks on the bottom. The screen should have a height 12 blocks and a width of 15 blocks.

Is there a way I can create a grid that is 15x12 with a cell size of 64x64 using 2d arrays? Because eventually, I want to add blocks to random cell locations in the grid(besides the fixed top and bottom rows)

I am looking for tutorials on how to do this, but I am finding people that use other open source options that are not included in swift. Please drop any tips or advice you have for me to tackle this I am very new to SpriteKit and Swift, thank you! (lmk if you need more clarification as well)

update: I got it to look like this now, but I don't know how to remove the rest of the blocks that arent in the top and bottom rows. How would i get the location of each block? enter image description here

  for i in 0...12{
            for j in 0...16{

            let block = SKSpriteNode(texture: blockImage, size: blockSize)
                block.position.x = block.frame.width/2 + CGFloat((64*j))
                block.position.y = frame.height - block.frame.height/2 - CGFloat((64*i))
                block.zPosition = 1
                addChild(block)
        }
        }


Solution 1:[1]

I don't really code for SpriteKit but maybe can offer some tips based on the logic I see.

One way could be to add some logic in the for loop to check if you are currently iterating the first 2 rows or the last row and only in these cases, add the row of blocks.

let rows = 12
let columns = 16

let topBoundary = 1

for i in 0...rows {
    for j in 0...columns {
        
        if i <= topBoundary || i == rows {
            let block = SKSpriteNode(texture: blockImage, size: blockSize)
            block.position.x = block.frame.width/2 + CGFloat((64*j))
            block.position.y = frame.height - block.frame.height/2 - CGFloat((64*i))
            block.zPosition = 1
            addChild(block)
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shawn Frank