How to write an equal method for private enumeration in Swift

I am new to Swift and have been trying to write a private enum that matches Equatable. Here is a simplified view of my code:

class Baz { /* Other members in class Baz */ private enum Test: Equatable { case Foo case Bar } private func == (lhs: Test, rhs: Test) -> Bool { //comparison } } 

On the method line "==", the compiler complains "Operators are allowed only in the global scope." And when I change the enumeration method and the "==" method for the public, then move the "==" from the class, then the errors will disappear.

My question is, what is the correct way to implement the "==" method for private enumeration?

Any help is appreciated.

========

Edit:

Thanks for helping me. I did not indicate that my personal enumeration and the function above are in the class .. (Code updated)

+6
source share
3 answers

I tried on the playground and this works for me:

 private enum Test: Equatable { case Foo case Bar } private func ==(lhs: Test, rhs: Test) -> Bool { return true } class A { func aFunc() { let test: Test = .Foo let test2: Test = .Foo if (test == test2) { print("Hello world") } } } let a = A() a.aFunc() // Hello world 

Can you change your question using your code? Therefore, I can edit my answer according to your problems.

+2
source

Although you may not be immediately useful to you, it is worth noting that from beta 5 in Swift 3 you can do this static func inside this type. See Xcode 8 Beta Release Notes for

Operators can be defined inside types or extensions. For instance:

  struct Foo: Equatable { let value: Int static func ==(lhs: Foo, rhs: Foo) -> Bool { return lhs.value == rhs.value } } 

Such statements must be declared as static (or inside a class, class final ) and have the same signature as their global copies.

This also works with enum types. Thus:

 private enum Test: Equatable { case foo case bar static func ==(lhs: Test, rhs: Test) -> Bool { // your test here } } 

And it even works when this Test implemented in a different type.

+3
source

There is nothing wrong with what you did:

 private enum Test: Equatable { case Foo case Bar } private func ==(lhs: Test, rhs: Test) -> Bool { // Put logic here } private let test = Test.Foo private let test2 = Test.Foo if (test == test2) { print("Hello world") } 

See this article for more details .

+1
source

All Articles