Initialising array of array

There's two problems here - one Swift and one SwiftUI.

Your SwiftUI problem is that your @State's initalValue should be a constant:

The Swift problem (the reason it won't compile) is this line:


_selectedSoilTypes[bore] = State(initialValue: ...)

Before you assign a value to the _selectedSoilTypes array at an index, you need to initialize the _selectedSoilTypes array.

So you’d need a line like this to satisfy the compiler:


// This will compile but still has the SwiftUI problem

_selectedSoilTypes = State(initalValue: ...)

Only after you give the array a value can you assign to the indices. But again, even it you get it to compile with this method the UI will not work correctly - you shouldn't assign the @State's initialValue in your init. I'm not sure exactly what you're trying to do here without more context so I'm not sure what to suggest instead.

3 Likes