1

I get the following compiling error: "Variable 'self.entryData' used before being initialized" How can I fix it and initialise the @state var entryData correctly in my init method?

struct EditEntryView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @State var entryData: EditEntryData
    @ObservedObject var moneyEntry: MoneyEntry
    
    init(entry: MoneyEntry) {
        moneyEntry = entry
        let iOwe = entry.value < 0 ? true : false
        let value = abs(entry.value)
        
        
        entryData = EditEntryData(info: entry.infos, value: String(value), date: entry.date, iOwe: iOwe)
    }
}

struct EditEntryData {
    var info: String = ""
    var value: String = ""
    var date: Date = Date()
    var iOwe: Bool = false
}

hfs23
  • 125
  • 1
  • 1
  • 9
  • What is EditEntryData? Can you please add here – Krunal Nagvadia Jul 14 '21 at 12:54
  • EditEntryData is a simle struct. I added the structs definition to the question – hfs23 Jul 14 '21 at 12:57
  • You cannot initialise a `@State` variable in the initialiser. State is private to the view and needs to be initialised inline in the declaration, outside the initialiser: `@State var entryData = EditEntryData(...)`. If you cannot do this, it's simply not "state". Put this value into a redesigned `@ObservedObject` class. – CouchDeveloper Jul 14 '21 at 14:48

1 Answers1

1

You need to initialise state itself, like

    _entryData = State(initialValue: 
         EditEntryData(info: entry.infos, 
         value: String(value), date: entry.date, iOwe: iOwe))
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • A View is a function! This would create a new state variable whenever the view will be initialised, i.e. whenever it needs to be rendered. That would defeat the purpose of `@State` which is meant to manage state which is kept alive through several lifecycles, ie. calling the render function. – CouchDeveloper Jul 14 '21 at 14:37