Home > Software design >  Need data to initialize a StateObject
Need data to initialize a StateObject

Time:03-06

I have a StateObject which I need to initialize with properties from Settings:

@State private var settingsStore = SettingsStore()
@StateObject var matrix = Matrix(d: settingsStore.d)

How do I do this? I can't make it a computed property because it's a state object

CodePudding user response:

I believe you are trying to use these properties inside a View.

To solve your problem, you can simply split your code in two different views, where in the first one you define the SettingsStore instance, then you use it to initialise the Matrix instance of the second view.

Like this:

struct FirstView: View {
    @State private var settingsStore = SettingsStore()
    
    var body: some View {
        SubView(settingsStore: $settingsStore, matrix: Matrix(d: settingsStore.d))
    }
}

struct SubView: View {
    @Binding var settingsStore: SettingsStore
    @StateObject var matrix: Matrix
    
    var body: some View {
        Text(matrix.d)
    }

}
  • Related