【问题标题】:Swift Array firstIndex & Equatable [closed]Swift Array firstIndex & Equatable [关闭]
【发布时间】: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 哎呀,我没仔细看。

标签: ios arrays swift


【解决方案1】:

正如 vadian 所说,=== 不是相等运算符。它是“相同实例”运算符。两个“相等”的类实例(根据 Equatable)如果不是同一个对象,则将失败 ===

根据您的描述,您应该可以使用firstIndex(of: item) 而不是firstIndex(where:)。但是在实现== 时也要非常小心,只使用一个可变ID。这允许两个对象具有不同的属性,但仍然根据 Equatable 比较“相等”(因此在所有上下文中都可以互换)。通常,您不应在 == 中对可变对象或两个对象尽管具有相同标识符但可能不同的任何情况进行部分属性检查。

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 2021-07-25
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多