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?

Asperi
  • 123,447
  • 8
  • 131
  • 245
Ian
  • 43
  • 2
  • There is no `themeData` declaration in provided code - would you show how you pass it in? Is it global variable? – Asperi Apr 20 '20 at 10:05
  • themeData is from an Array following the Class, called themeModel: – Ian Apr 20 '20 at 10:15
  • import SwiftUI let themeData: [themeModel] = [ themeModel(titleL1: "", titleL2: "", subHead: ""), – Ian Apr 20 '20 at 10:15

2 Answers2

1

do your

theme: themeModel = themeData[countRecognizer.themeCount]

in

.onAppear(...)
workingdog
  • 3,125
  • 1
  • 5
  • 13
  • 1
    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` – Tiziano Coroneo Apr 20 '20 at 10:19
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
Tiziano Coroneo
  • 601
  • 4
  • 16
  • 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)? – Ian Apr 20 '20 at 21:05
  • `themeCounter.theme` ? – Tiziano Coroneo Apr 22 '20 at 14:51