我正在运行这段代码
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 forFresh 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 = []
}
编辑:我如何填充数据?
ComboOption
,每个都包含许多 ComboOptionDish
es。ComboOptionDish
es,我将其添加到 selectedComboOptionDishes
这是 ComboOptionDish
的 Set()
code>es 里面对应的ComboOption
ComboOption
是否相等,所以我需要为 ComboOption
我无法重现您的问题,但我相信这是平等过载的错误。有一个类似的话题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/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) | Powered by Discuz! X3.4 |