Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write an equal method for private enum in Swift

Tags:

enums

swift

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)

like image 409
user3291342 Avatar asked Aug 11 '16 22:08

user3291342


People also ask

Can Swift enums have methods?

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.

Can enum conform to Swift protocol?

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.

Can we extend enum in Swift?

A Swift extension allows you to add functionality to a type, a class, a struct, an enum, or a protocol.

What is Rawvalue in Swift?

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.


Video Answer


1 Answers

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.

like image 60
Rob Avatar answered Sep 28 '22 05:09

Rob