Search code examples
swiftequatable

Implement Equatable for custom private class - Swift


I know how to implement Equatable for a non-private class (by writing the == operator function), however this doesn't work for a private class given that "Operators are only allowed at global scope". Problem is, at global scope, private class is not visible, so how can I implement its == operator..?

private class Foo : Equatable{
    var bar = ""
}

func == (lhs: Foo, rhs: Foo) -> Bool {
        return lhs.bar == rhs.bar
}

error: Use of undeclared type Foo


Solution

  • You need to also declare your == operator function as private for this to work. Functions are by default scoped as internal, and you can't have an internal method with privately scoped parameters or return type.

    private class Foo : Equatable {
        var bar = ""
    }
    
    private func ==(lhs: Foo, rhs: Foo) -> Bool {
            return lhs.bar == rhs.bar
    }