【发布时间】:2021-12-31 02:04:36
【问题描述】:
我在 Swift 中有以下课程
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 哎呀,我没仔细看。