1
votes

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)")
                }
            }
        }
    }
}
1
ForEach is a view container, not a control flow. Use instead standard swift for in somewhere outside of body.Asperi

1 Answers

1
votes

ForEach is meant to be used for building repeating content, body is just for defining your View not for performing any calculations.

The easiest way to calculated the number of walks is to declare a computed property inside SummaryView but outside body:

var walksCount: Int {
    eventsRepository.events?
        .filter { $0.title.contains("Walk") }
        .count ?? 0
}

Then you can than use it inside the body like this:

 Text("Walks:\(walksCount)")