0

I have the two following arrays:

// Customers
let customers: [Customer] = [
    Customer(id: 1, firstname: "John", lastname: "Doe"),
    Customer(id: 2, firstname: "Jane", lastname: "Doe"),
    Customer(id: 3, firstname: "James", lastname: "Doe")
]

// Subscriptions
let subscriptions: [Subscription] = [
    Subscription(id: 1, costs: 1000, subTemplate: subscriptionTemplates[0], owner: customers[0]),
    Subscription(id: 2, costs: 700, subTemplate: subscriptionTemplates[1], owner: customers[0]),
    Subscription(id: 3, costs: 1200, subTemplate: subscriptionTemplates[6], owner: customers[1])
]

Now I want to make a list with all the customers that have an active subscription.

I've tried the following:

// List with all active subscriptions
List {
    ForEach(customers) { customer in
        ForEach(subscriptions) { sub in
            if(sub.owner == customer) {
                NavigationLink(destination: CustomerAboDetailView()) {
                    AboListItemView(customer: customer)
                }
            }
        }
                        
    }
}

I get the following error:

Binary operator '==' cannot be applied to two 'Customer' operands

Does anyone know a method to solve this problem?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Janik Spies
  • 399
  • 7
  • 15
  • 2
    implement https://developer.apple.com/documentation/swift/equatable for Customer – ezaji Dec 03 '20 at 09:37
  • Does this answer your question? [Binary operator '==' cannot be applied to two operands](https://stackoverflow.com/questions/34640685/binary-operator-cannot-be-applied-to-two-operands) – ezaji Dec 03 '20 at 09:39

1 Answers1

3

You can make your Customer model conform to Equatable and you can check if two objects are equal

class Customer {
    var id : Int
    var firstname : String
    var lastname : String
    
    init(id: Int, firstname: String, lastname : String) {
        self.id = id
        self.firstname = firstname
        self.lastname = lastname
    }
}

extension Customer: Equatable {
    static func == (lhs: Customer, rhs: Customer) -> Bool {
        return
            lhs.id == rhs.id //<< predicate when two objects are same
    }
}
davidev
  • 7,694
  • 5
  • 21
  • 56