'ForEach in SwiftUI: Error "Missing argument for parameter #1 in call"

I'm still trying to create a calendar app and ran into another problem I wasn't able to find a solution for online.

Xcode throws the error "Missing argument for parameter #1 in call" in line 2 of my code sample. I used similar code at other places before, but I can't find the difference in this one.

Also this code worked before and started throwing this error after I moved some code to the new View DayViewEvent after getting the error "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions", which I hoped to fix it and would be clean code anyway.

For reference: events is an optional array of EKEvents (hence the first if) and selectedDate is (obviously) a Date.

Any help is greatly appreciated!

if let events = events {
    ForEach(events, id: \.self) { event in
        if !event.isAllDay {
            DayViewEvent(selectedDate: selectedDate, event: event)
        }
    }
}


Solution 1:[1]

The body func is called on every state change so needs to be as fast as possible thus the data needed should already be processed. So need to filter your events in a func or block, e.g. in onAppear:

struct EventsView: View {

    @State var events = [Events]()

    var body: some View {
        ForEach(events, id: \.eventIdentifier) { event in
            DayViewEvent(event: event)
        }
        .onAppear {
            events = EventsDB.shared.events(isAllDay: false)
        }
    }
}

And by the way, since you are using id: \.self because event is a reference type you need to ensure when retrieving the events that the same event always returns the same instance and not a new instance. If unique instances are returned then you need to instead use an id that is a unique property, e.g. id: \.eventIdentifier.

Also you should know that the SwiftUI declarative syntax inside body is not like normal programming, the ifs and for loops all generate some very complex code, e.g. _ConditionalContent when an if is used, read up on it here: https://swiftwithmajid.com/2021/12/09/structural-identity-in-swiftui/ or watch Apple's WWDC video Demystify SwiftUI.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1