I'm trying to filter an array of Deals with a status DealStaus which has a nested array of Bookings, each one with a BookingStatus.
I want to filter Deals with status .won and Bookings according to the statuses given when calling the function. BookingStatus and DealStatus are both enums.
Deal and Booking look like this:
public struct Deal: Decodable {
public let identifier: String?
public let status: DealStatus
public let bookings: [Booking]?
}
public struct Booking: Decodable {
public let identifier: String?
public let status: BookingStatus
public let startDate: Date?
public let endDate: Date?
}
To do so I wrote the following snippet:
private func getDeals(with bookingStatus: [BookingStatus]) -> [Deal] {
guard let user = currentUser, let deals = user.deals else { return [Deal]() } // Note: user is a class attribute
return deals.filter { $0.status == .won && $0.bookings?.filter { bookingStatus.contains($0.status) }}
}
This does not work. The compiler gives the following error:
Optional type '[Booking]?' cannot be used as a boolean; test for '!= nil' instead
$0.bookings?.filter { bookingStatus.contains($0.status) }is an array. What is needed here is a Boolean, i,e, true or false.Dealthat does the check and returns a boolean so you could call... && $0.checkBookings(bookingStatus)DealandBooking