[英]Swift Array firstIndex & Equatable
我在 Swift 中有以下 class
public class ItemModel:Identifiable, Equatable, Loadable {
public static func == (lhs: ItemModel, rhs: ItemModel) -> Bool {
return lhs.id == rhs.id
}
public var id:UUID
public init() {
self.id = UUID()
}
}
然后我有子类
public class SubItemModel:ItemModel {
}
我有一个 [SubItemModel] 类型的数组layerItems 。 当我测试以下代码时
public func removeItem(_ item:SubItemModel) -> Bool {
//This line fails despite $0 and item having same id, why?
if let index = layerItems.firstIndex(where: {$0 === item}) {
item.cleanup()
layerItems.remove(at: index)
return true
}
}
return false
}
它返回false ,因为 firstIndex(where:...) 返回 nil。 尽管数组中存在具有给定 id 的项目,但为什么会这样?
正如 vadian 所指出的, ===
不是等式运算符。 它是“相同实例”运算符。 两个“相等”(根据 Equatable)的 class 实例将失败===
如果它们不是相同的 object。
根据您的描述,您应该能够使用firstIndex(of: item)
而不是firstIndex(where:)
。 但也要非常小心地实现==
仅使用可变 ID。 这允许两个对象具有不同的属性,但仍然根据 Equatable 比较“相等”(因此在所有上下文中都可以互换)。 您通常不应该在==
中对可变对象进行部分属性检查,或者在两个对象可能不同但具有相同标识符的任何情况下进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.