App crashed

Hello there! I was trying to build an app with the new App feature in Swift Playgrounds for Mac. But I have an error message in my code, and I can't understand how to fix it. Can anyone help me to solve this error.

Here's the code:

import SwiftUI

struct Something: View {

    let rows = 17
    let columns = 17
    let size: CGFloat = 10
    let blocks: [[Color]] = [[.purple, .purple]]


    var body: some View {
        VStack {
            ForEach((0...self.rows - 1), id: \.self) { row in 
                HStack (spacing: 0) {
                    ForEach((0...self.columns - 1), id: \.self) { col in
                        VStack (spacing: 0) {
                            Rectangle()
                                .frame(width: self.size, height: self.size)
                                .foregroundColor(self.blocks[row][col])  // index out of range: the requested index was outside the bounds of the array.
                        }
                    }
                }
            }
        }
    }
}



In your snippet, blocks is an array of arrays, which you’re treating like a two-dimensional array. Both row and col values range from 0 to 16. However, your blocks array has a row count of 1 and a column count of 2. Hence the out of bounds trap.

In short, you need many more values in blocks. Or you need to reduce the range of row and col.

For the former, you can use repeatedElement(_:count:):

let blocks = [[Color]](repeatElement([Color](repeatElement(Color.purple, count: columns)), count: rows))

Oh, one last thing: Swift supports half open ranges, so you can write this:

0...self.rows - 1

as this:

0..<self.rows

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

App crashed
 
 
Q