swift对象中的自定义相等性,保留了与传统Objective-C代码的兼容性

Gab*_*lla 40 equality swift

在Objective-C中你会做一些事情

- (BOOL)isEqual:(id)other {
    if (other == self)
        return YES;
    if (!other || ![other isKindOfClass:[self class]])
        return NO;
    return [self.customProperty isEqual:other.customProperty];
}
Run Code Online (Sandbox Code Playgroud)

我在斯威夫特的第一次天真尝试如下

func isEqual(other: AnyObject) -> Boolean {
    if self === other {
        return true
    }
    if let otherTyped = other as? MyType {
        return self.myProperty == otherTyper.myProperty
    }
    return false
}
Run Code Online (Sandbox Code Playgroud)

但我对此并不满意.我甚至不知道签名是否正确,或者我们是否应该使用不同的签名isEqual.

有什么想法吗?

编辑:我也想保持Objective-C兼容性(我的类用于遗留的Obj-C代码和新的Swift代码).所以我认为只有压倒==是不够的.我错了吗?

nsc*_*hum 68

是的,您需要覆盖isEqual(和hash)以使您的对象完全兼容Objective-C.这是一个适用于语法的Playground准备示例:

import Foundation

class MyClass: NSObject {

    var value = 5

    override func isEqual(object: AnyObject?) -> Bool {
        if let object = object as? MyClass {
            return value == object.value
        } else {
            return false
        }
    }

    override var hash: Int {
        return value.hashValue
    }
}

var x = MyClass()
var y = MyClass()
var set = NSMutableSet()

x.value = 10
y.value = 10
set.addObject(x)

x.isEqual(y) // true
set.containsObject(y) // true
Run Code Online (Sandbox Code Playgroud)

(Xcode 6.3中的语法当前)


Gre*_*egg 9

您还可以实现自定义equatable,例如:

func == (lhs: CustomClass, rhs: CustomClass) -> Bool {
     return lhs.variable == rhs.variable
}
Run Code Online (Sandbox Code Playgroud)

这将允许您简单地检查这样的相等:

let c1: CustomClass = CustomClass(5)
let c2: CustomClass = CustomClass(5)

if c1 == c2 { 
    // do whatever
}
Run Code Online (Sandbox Code Playgroud)

确保您的自定义equable超出了类范围!