4

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?

3
  • There is no themeData declaration in provided code - would you show how you pass it in? Is it global variable? Commented Apr 20, 2020 at 10:05
  • themeData is from an Array following the Class, called themeModel: Commented Apr 20, 2020 at 10:15
  • import SwiftUI let themeData: [themeModel] = [ themeModel(titleL1: "", titleL2: "", subHead: ""), Commented Apr 20, 2020 at 10:15

2 Answers 2

1

do your

theme: themeModel = themeData[countRecognizer.themeCount]

in

.onAppear(...)
Sign up to request clarification or add additional context in comments.

1 Comment

this won't fix the issue, as themeModel is non optional. It will work if you make var theme: themeModel?, but at that point you have to make a view that supports having nil as a theme
0

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

2 Comments

Thanks, Mate. My main issue is to control the ThemeData input with a gesture. The environmentobject was an approach. If I put "var theme" inside the ThemeCounter as a published, how can I pass it to videoCard(theme: theme)?
themeCounter.theme ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.