CWineland CWineland - 1 year ago 106
Swift Question

Checking for nill equality in custom == operator

So I have a custom operator for equality on a class, i want to return true if they are both nil however my operator gets called when i ask if left or right == nil. Is there another or better way to do this?

public func == (left: classXYZ?, right: classXYZ?) -> Bool {
if left == nil && right == nil {
return true
if left != nil && right != nil {
return left!.uniquID == right!.uniquID
return false

Answer Source

Here's the code to make your class Equatable

class ClassXYZ: Equatable {
    let uniqueID: String

    init(uniqueID: String) {
        self.uniqueID = uniqueID

func ==(left: ClassXYZ, right: ClassXYZ) -> Bool {
    return left.uniqueID == right.uniqueID

You don't need (and you can't) to explicitly specify that nil == nil is true, it is already built into Swift, look

let a: ClassXYZ? = nil
let b: ClassXYZ? = nil

print(a == b) // true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download