使用ObjectIdentifier()和'==='运算符之间的区别

Nic*_*ari 7 swift equatable

假设我在Swift中实现了一个根类,我声明它采用了Equatable协议(我希望能够判断我的类型的数组是否包含给定的实例).

有什么区别 - 在这种特定情况下 - 在实现协议所需的==运算符之间有什么区别:

public static func ==(lhs: MyClass, rhs: MyClass) -> Bool {

    return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
Run Code Online (Sandbox Code Playgroud)

......而不是这样做:

public static func ==(lhs: MyClass, rhs: MyClass) -> Bool {

    return (lhs === rhs)
}
Run Code Online (Sandbox Code Playgroud)

作为参考,这是文档所说的ObjectIdentifier():

类实例或元类型的唯一标识符.在Swift中,只有类实例和元类型具有唯一的标识.结构,枚举,函数或元组没有身份概念.

......这就是Swift编程语言(Swift 3)的"基本操作符"部分对===运算符的说法:

注意

Swift还提供了两个标识运算符(===和!==),用于测试两个对象引用是否都引用同一个对象实例.有关更多信息,请参阅类和结构.

Mar*_*n R 10

类实例没有区别,请参阅ObjectIdentifier.swift中的以下 注释:

  /// Creates an instance that uniquely identifies the given class instance.
  ///
  /// The following example creates an example class `A` and compares instances
  /// of the class using their object identifiers and the identical-to
  /// operator (`===`):
  ///
  ///     class IntegerRef {
  ///         let value: Int
  ///         init(_ value: Int) {
  ///             self.value = value
  ///         }
  ///     }
  ///
  ///     let x = IntegerRef(10)
  ///     let y = x
  ///
  ///     print(ObjectIdentifier(x) == ObjectIdentifier(y))
  ///     // Prints "true"
  ///     print(x === y)
  ///     // Prints "true"
  ///
  ///     let z = IntegerRef(10)
  ///     print(ObjectIdentifier(x) == ObjectIdentifier(z))
  ///     // Prints "false"
  ///     print(x === z)
  ///     // Prints "false"
  ///
Run Code Online (Sandbox Code Playgroud)

从for的实现中==ObjectIdentifier也可以看出 ,它只是比较指向对象存储的指针:

  public static func == (x: ObjectIdentifier, y: ObjectIdentifier) -> Bool {
    return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value))
  }
Run Code Online (Sandbox Code Playgroud)

这正是该===操作 确实还有:

public func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return Bool(Builtin.cmp_eq_RawPointer(
        Builtin.bridgeToRawPointer(Builtin.castToUnknownObject(l)),
        Builtin.bridgeToRawPointer(Builtin.castToUnknownObject(r))
      ))
  case (nil, nil):
    return true
  default:
    return false
  }
}
Run Code Online (Sandbox Code Playgroud)

ObjectIdentifier符合Hashable,所以如果你想为你的类实现该协议是有用的:

extension MyClass: Hashable {
    var hashValue: Int {
        return ObjectIdentifier(self).hashValue
    }
}
Run Code Online (Sandbox Code Playgroud)

还可以为未定义的元类型(例如ObjectIdentifier(Float.self))创建对象标识符===.

  • `===`运算符[现在直接比较](https://github.com/apple/swift/blob/b330c6078fd233ea7206158a20b21b4672d75cc3/stdlib/public/core/Equatable.swift#L249)参数的ObjectIdentifier`. (3认同)