4
votes

I try to pass data from an @environmentObject to a @State object in the TopLevel

struct ContentView: View {

    @EnvironmentObject var countRecognizer: themeCounter
    @State var theme: themeModel = themeData[countRecognizer.themeCount]

    @State var hideBar = true

    var body: some View {
        ZStack {
            videoCard(theme: theme)
                .statusBar(hidden: true)

            Text("\(self.countRecognizer.themeCount)")

            if hideBar == true {

            }
        }

But I am getting this error: "Cannot use instance member within property initializer; property initializers run before 'self' is available"

the themeData Array should get the Int from the environment Object.

How can I fix this problem?

2
There is no themeData declaration in provided code - would you show how you pass it in? Is it global variable? - Asperi
themeData is from an Array following the Class, called themeModel: - Ian
import SwiftUI let themeData: [themeModel] = [ themeModel(titleL1: "", titleL2: "", subHead: ""), - Ian

2 Answers

1
votes

do your

theme: themeModel = themeData[countRecognizer.themeCount]

in

.onAppear(...)
0
votes

You cannot use countRecognizer directly from the initial value of another property, and there is no easy fix.

I suggest you to look into refactoring your @State var theme property into a @Published var theme inside the themeCounter ObservableObject. Apple tutorials will help you: https://developer.apple.com/tutorials/swiftui/tutorials

As an aside: DON'T NAME TYPES WITH A LOWERCASE.

  • themeModel should be ThemeModel
  • themeCounter should be ThemeCounter
  • videoCard should be VideoCard