Learn Courses My Dashboard

ForEach UI problem

I’m having problems with one of my views. The compiler error is: “Failed to produce diagnostic for expression”

I think the issue is that it is trying to run a ForEach loop before the model and data are set up. The JSON seems to be parsing OK. I don’t want to call the getData functions until this view gets navigated to, to reduce background processing.

This is the navigation link code for the parent view:

                    NavigationLink(
                        destination: WhatsHappeningView(),
                        label: {
                            HomeViewRow(imageToShow: "happening", textToShow: "What's happening", descriptionText: "Find out the latest about what's happening including upcoming events, classes and challenges")
                        })

Here is the basic model:

import Foundation

struct Event: Decodable {
    
    var eventDay: Int?
    var eventMonth: Int?
    var eventYear: Int?
    var eventTime: Int?
    var eventDuration: Int?
    var eventDescription: String?
    var eventLink: String?
    var eventImage: String?

}

Here is my ViewModel:


import Foundation

class EventModel: ObservableObject {
    
    @Published var eventList = [Event]()
    
    init() {
        
        self.eventList = getEventData()
    }
    
    func getEventData() -> [Event] {
        
        self.eventList = [Event]()
        
        // get json data
        let jsonUrl = Bundle.main.url(forResource: "TestEventsData", withExtension: ".json")
        
        
        do {
            
            let jsonData = try Data(contentsOf: jsonUrl!)
            
            let decoder = JSONDecoder()
            
            let events = try decoder.decode([Event].self, from: jsonData)

            
            print("Parsed correctly")
            return events
            
            
        } catch {
            
            print(error)
            
        }
        
        return [Event]()
        
        
        
    }
}

And here is the View:

import SwiftUI

struct WhatsHappeningView: View {
    
    var eventsModel = EventModel()
    
    var body: some View {
        
        ScrollView {
            
            VStack (alignment: .leading) {
                Text("The latest information on events, classes and challenges.")
                    .font(.footnote)
                    .padding(.bottom, 20)
                
                
                // TODO: Get events data from JSON file
                
                Divider()
                
                ForEach (eventsModel.eventList) { e in
                    Text(e.eventDescription ?? "")
                }
                
                
            }
            .padding()
            
            
            
        }.navigationTitle("Wellbeing")
    }
    
    
}

Event needs to be made Identifiable in order to be used in the ForEach the way you have.

Thank you - that has fixed it! Much appreciated.