iosarraysswiftinitialization

Why am I getting "Variable 'grid' used before being initialized" error despite having an init?


I'm struggling to understand why I'm getting a compiler error ("Variable 'grid' used before being initialized") on the following Xcode Swift Playground.

[I will apologize in advance, I am a Swift noob. Thanks for helping!]

I have created the following in an iOS Playground in Xcode 10.3.

I'm trying to create a two dimensional grid (10 by 10) of cells, with each cell containing some specific attributes (e.g., value, providedByUser, etc). I have provided initial values for the attributes of each cell. I have also have an init() for the creation of the grid itself. That init() will, hopefully, create me the 10 by 10 grid I am after.

However, I keep getting the error message when I ask to print my grid after declaring it.

import UIKit

struct Cell
{
    var value: Int = 0
    var providedByUser: Bool = false
    var options: [Int] = [0]
    var guess: Int = 0
}

struct MatrixGrid
{
    var grid: [[Cell]]
    init() {
        grid = Array(repeating: Array(repeating: Cell(value: 0, providedByUser: false, options: [0], guess: 0), count: 10), count: 10)
    }
}

var myGrid: MatrixGrid
print(myGrid)

The Playground says "Variable 'myGrid' used before being initialized" on the print line.

The console provides the following:

error: Grid.playground:20:7: error: variable 'myGrid' used before being initialized print(myGrid) ^

Sudoku Grid.playground:19:5: note: variable defined here var myGrid: MatrixGrid ^


Solution

  • You've declared a variable of type MatrixGrid, but you've never initialized it. It doesn't have a value, because you didn't set one. Naturally, it needs to have a value before you can use its value.