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.
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.
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.
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.
A Swift extension allows you to add functionality to a type, a class, a struct, an enum, or a protocol.
Yes, according to the documentation.
The synthesized allCases collection provides the cases in order of their declaration.
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