Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of cases in an enum that conforms to CaseIterable protocol in Swift?

Tags:

enums

swift

Is the order of cases in an enum that conforms to CaseIterable protocol guaranteed to be the order in which it was declared ?

enum MyEnum: CaseIterable {
    case test
    case foo
    case bar
    case play
}

print(MyEnum.allCases)

will print:

[MyEnum.test, MyEnum.foo, MyEnum.bar, MyEnum.play]

I want to know if this order is guaranteed.

From this blog we can see that the way swift compiler parses, the order is guaranteed. But I could not find any documentation that this behaviour is guaranteed and not subject to change.

P.S. This is not a case of XYZ problem. I just want to know about this particular behaviour in Swift.

like image 861
May Rest in Peace Avatar asked Aug 01 '19 04:08

May Rest in Peace


People also ask

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.

How do I get all enum cases?

To enable it, all you need to do is make your enum conform to the CaseIterable protocol and at compile time Swift will automatically generate an allCases property that is an array of all your enum's cases, in the order you defined them.

What does the CaseIterable protocol do?

CaseIterable Protocol This follows the pattern of Equatable, Comparable and Hashable by having the compiler automatically synthesize the implementation. The compiler then provides you an allCases that is a collection of all cases of the enum: Direction.

Can enum be extended Swift?

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


1 Answers

Yes, according to the documentation.

The synthesized allCases collection provides the cases in order of their declaration.

like image 82
Adrian Avatar answered Oct 05 '22 18:10

Adrian