I simply want to count the number of events that fit an "if" statement within a ForEach loop, but am getting the following error.
I have tried several variations to achieve the task but each has resulted in errors of some description. I'll add that I am a struggling novice!
Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
The code I'm using right now.
import Foundation
import SwiftUI
import EventKit
class Summary: ObservableObject {
@Published var walkCount:Int = 0
@Published var dayCareCount:Int = 0
@Published var shortStayCount:Int = 0
@Published var longStayCount:Int = 0
@Published var dropInCount:Int = 0
}
struct SummaryView: View {
@ObservedObject var eventsRepository = EventsRepository.shared
@ObservedObject var selectDate = datepicker()
var summary: Summary
enum BookingType {
case walk
case dayCare
case shortStay
case longStay
case dropIn
}
func countBooking(bookingType: BookingType) {
switch bookingType {
case .walk:
summary.walkCount += 1
case .dayCare:
summary.dayCareCount += 1
case .shortStay:
summary.shortStayCount += 1
case .longStay:
summary.longStayCount += 1
case .dropIn:
summary.dropInCount += 1
}
}
var body: some View {
GroupBox {
VStack{
//Walks
HStack{
ForEach(eventsRepository.events ?? [], id: \.self) { event in
if event.title.contains("Walk") {
countBooking(bookingType: .walk) // running function results in error
}
}
Text("Walks:\(summary.walkCount)")
}
}
}
}
}
ForEach
is a view container, not a control flow. Use instead standard swiftfor in
somewhere outside ofbody
. – Asperi