Reputation: 1953
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
Upvotes: 0
Views: 1781
Reputation: 1953
Following the instructions of @matt, I broke it down:
private func getDeals(with bookingStatus: [BookingStatus]) -> [Deal] {
guard let user = currentUser, let deals = user.deals else { return [Deal]() }
return deals
.filter { $0.status == .won }
.filter { $0.bookings?.contains(where: { bookingStatus.contains($0.status)} ) ?? false }
}
Upvotes: 5