【问题标题】:Swift filter over array reference快速过滤数组引用
【发布时间】:2020-12-03 09:31:50
【问题描述】:

我有以下两个数组:

// 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])
]

现在我想列出所有拥有有效订阅的客户。

我尝试了以下方法:

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

我收到以下错误:

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

有人知道解决这个问题的方法吗?

【问题讨论】:

标签: swift swiftui


【解决方案1】:

您可以使您的 Customer 模型符合 Equatable 并且您可以检查两个对象是否相等

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
    }
}

【讨论】:

    猜你喜欢
    • 2015-10-27
    • 2014-09-11
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多