究竟如何==使用Set() - Swift

时间:2016-06-19 15:45:55

标签: ios swift set

我正在运行此代码

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
[]
  

为什么=()Set()在索引1上返回false(这里第二个)?为什么==阻止Fresh Lemon Juice阻止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 } ???   我究竟做错了什么?或者= =在Set()上运行的方式有何不同?

我的ComboOptionDish类是

class ComboOption: Mappable, Equatable {

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

}

我的ComboOption类是

ComboOption

编辑:我如何填写数据?

  • 我使用ObjectMapper使用JSON填充数据。
  • 我有很多ComboOptionDish个,每个都包含许多ComboOptionDish es。
  • 然后我让用户选择selectedComboOptionDishes es,我添加到Set()这是ComboOptionDish ComboOptionComboOption内的==
  • 然后我现在需要比较两个ComboOption是否相等,所以我需要覆盖var urls=["http://Url1.com","http://Url2.com","http://Url3.com"] $.get(ulrs[0]).done(function () { alert("success"); }).fail(function () { alert(" First failed!, try with second"); $.get(ulrs[1]).done(function () { alert("success"); }).fail(function () { alert("Second failed! Try with third..."); $.get(ulrs[2]).done(function () { alert("success"); }).fail(function () { alert("All failed!"); }); }); }); 的{​​{1}}

1 个答案:

答案 0 :(得分:0)

我无法重现你的问题,但我相信这是一个平等超载的错误。有关于它的类似主题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
        }
    }
}