OStack程序员社区-中国程序员成长平台

标题: ios - == 究竟如何与 Set() 一起工作 - Swift [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 16:45
标题: ios - == 究竟如何与 Set() 一起工作 - Swift

我正在运行这段代码

if(left.comboOptions.count != right.comboOptions.count) {
    for index in 0...left.comboOptions.count-1  {
        print(left.comboOptions[index].selectedComboOptionDishes == right.comboOptions[index].selectedComboOptionDishes)
        print(left.comboOptions[index].selectedComboOptionDishes)
        print("vs")
        print(right.comboOptions[index].selectedComboOptionDishes)
        print()
    }
}

我得到的输出是

Comparing comboOptionDish
1x Black Beans Wrap(277) vs 1x Black Beans Wrap(277)
Both are equal

true
[1x Black Beans Wrap(277)]
vs
[1x Black Beans Wrap(277)]

false
[1x Fresh Lemon Juice(292)]
vs
[1x Fresh Lemon Juice(292)]

true
[]
vs
[]

Why is == on Set() returning false on index 1 (second one here)?? and Why is == block not executed for Fresh Lemon Juice??? What am I doing wrong? Or the way == operates on Set() differs specifically?

我的 ComboOptionDish 类是

class ComboOptionDish: Equatable, Hashable, CustomStringConvertible {

    var id: Int!
    var quantity: Int = 0
    var dish: Dish! /*Contains name, id and price and nothing else*/
    var description: String {
        return String(quantity) + "x " + dish.name + "(" + String(id) + ")"
    }

    var hashValue: Int {
        return self.id * self.quantity
    }
}

func == (left: ComboOptionDish, right: ComboOptionDish) -> Bool {
    print("Comparing comboOptionDish")
    print(String(left) + " vs " + String(right))
    if left.id != right.id { print("IDs not equal\n"); return false }
    if left.quantity != right.quantity { print("Quantity not equal\n"); return false }
    print("Both are equal")
    print()
    return true
}

我的 ComboOption 类是

class ComboOption: Mappable, Equatable {

    var id: Int!
    var name: String!
    var selectedComboOptionDishes: Set<ComboOptionDish> = Set()
    var comboOptionDishes: ComboOptionDish = []

}

编辑:我如何填充数据?



Best Answer-推荐答案


我无法重现您的问题,但我相信这是平等过载的错误。有一个类似的话题here .

解决方法是让 ComboOptionDish 子类 NSObject 并使用 isEqual

class ComboOptionDish: NSObject {
    override var description: String {
        //...
    }

    override var hash: Int {
        //...
    }

    override func isEqual(object: AnyObject?) -> Bool {
        if let other = object as? ComboOptionDish {
            return self.id == other.id && self.quantity == other.quantity
        } else {
            return false
        }
    }
}

关于ios - == 究竟如何与 Set() 一起工作 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908994/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4