大佬教程收集整理的这篇文章主要介绍了swift – 使用ObjectIdentifier()和’===’运算符之间的区别,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
有什么区别 – 在这种特定情况下 – 在实现协议的required ==运算符之间有什么区别:
public static func ==(lhs: MyClass,rhs: MyClass) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) }
……而不是这样做:
public static func ==(lhs: MyClass,rhs: MyClass) -> Bool { return (lhs === rhs) }
作为参考,这是文档中关于ObjectIdentifier()的内容:
…这就是The Swift Programming Language (Swift 3)的“基本运算符”部分对===运算符的说法:
/// 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" ///
从中也可以看出这一点
implementation of ==
for ObjectIdentifier
,
它只是比较指向对象存储的指针:
public static func == (x: ObjectIdentifier,y: ObjectIdentifier) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(x._value,y._value)) }
这是the ===
operator
也这样做:
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 } }
ObjectIdentifier符合Hashable,因此如果您想为您的类实现该协议,它会很有用:
extension MyClass: Hashable { var hashValue: Int { return ObjectIdentifier(self).hashValue } }
还可以为元类型创建对象标识符(例如,ObjectIdentifier(Float.self)),其中未定义===.
以上是大佬教程为你收集整理的swift – 使用ObjectIdentifier()和’===’运算符之间的区别全部内容,希望文章能够帮你解决swift – 使用ObjectIdentifier()和’===’运算符之间的区别所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。