Hi, VERY new to swift/swiftui and doing a favor for a friend ...
trying to initialize a member of an array of array of strings ... but get errors as follows:
Cannot assign value of type 'State<[String]>' to subscript of type '[String]'
Referencing subscript 'subscript(_:)' requires wrapped value of type '[[String]]'
any suggestions appreciated
code excerpts as follows:
....
var bore: Int // passed from calling view
...
// Constants
private let soilTypes = ["FILL", "SILT", "CLAY", "SAND", "XW ROCK", "DW ROCK"]
...
// allocated array of soil types Vs depth, one for each bore
@State private var selectedSoilTypes: [[String]]
....
// init stuff
init( bore: Int) {
// init the passed value and row count
self.bore = bore
let rowCount = 30
//init the soiltype [bore] array to def values
_selectedSoilTypes[bore] = State(initialValue: Array(repeating: soilTypes[0], count: rowCount))
This works for a single array but not for array of arrays ???
State generally never is used on its own, The @State declaration is sufficient. You can assign to the variable afterwards that same way you would a non-@State variable.
I haven't tested this, but I think you'd just want:
Thank you, im not sure I understand the "wrapper" concept of _ and $ and your suggestion gets rid of the wrapper error but not the first "subscript" error ...
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.
It's a little weird to wrap one's head around. Essentially, @State exists so SwiftUI can be told that an important variable which changes the View has changed.