I'm new to Swift and was trying to write a private enum that conforms Equatable. Here is a simplified representation 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 line of the "==" method, the compiler is complaining "Operators are only allowed at global scope". And when I change enum Test and "==" method to public then move the "==" out of the class, then the errors go away.
My question is what is the correct way to implement the "==" method for a private enum?
Any help is appreciated.
========
Edit:
Thanks all for helping me out. I didn't specify that my private enum and function above are in a class.. (Code is updated)
Swift's Enum can have methods. It can have instance methods and you can use it to return expression value for the UI. Let's look at the code above.
Yes, enums can conform protocols. You can use Swift's own protocols or custom protocols. By using protocols with Enums you can add more capabilities.
A Swift extension allows you to add functionality to a type, a class, a struct, an enum, or a protocol.
Enumerations in Swift are much more flexible, and don't have to provide a value for each case of the enumeration. If a value (known as a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.
While perhaps not immediately useful for you, it's worth noting that as of beta 5, in Swift 3 you can make this a static func
within the type. See the Xcode 8 Beta Release Notes, which says
Operators can be defined within types or extensions thereof. For example:
struct Foo: Equatable { let value: Int static func ==(lhs: Foo, rhs: Foo) -> Bool { return lhs.value == rhs.value } }
Such operators must be declared as
static
(or, within a class,class final
), and have the same signature as their global counterparts.
This works with enum
types, too. Thus:
private enum Test: Equatable {
case foo
case bar
static func ==(lhs: Test, rhs: Test) -> Bool {
// your test here
}
}
And this even works when this Test
is implemented within another type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With