Search code examples
classstructswiftuiinitialization

SwiftUi initialize the main struct in a class


I can't seem to be able to initialize the fest var below. I am getting the following error when doing so:

'self' used in property access 'fest' before all stored properties are initialized

My struct is:

struct Fest: Codable {
    let days, year: String
    let shows: [Show]
}

struct Show: Codable, Identifiable {
    let id = UUID() 
    let showName, stageName, description: String
    let times: [Int] 
    let isFavorite, oneNight: Bool
}

My class is:

class FestivalData: ObservableObject {
    @Published var fest: Fest
    @Published var shows: [Show] = []
    
    init() {
        self.fest = fest
    }
    
    func addShow (_ show: Show) {
        DispatchQueue.main.async { [self] in
            shows.append(show)
        }
    }

}

Solution

  • Thanks, but this still doesn't give me what I am trying to do. in the class I need to be able to add data to the fest var. The fest var is the main part of the data struct that needs to be updated. I was using @Published var shows: [Show] = [] because that works.

    fest.days = stringOfDays
    fest.shows.append(shows)
    

    similar to using the addShow function.

    in my ContentView I have: @StateObject var festivalData = FestivalData() and I get the following error: Missing argument for parameter 'fest' in call

    I don't have to put a parameter for the other published var.