16

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.

1 Answer 1

21

Yes, according to the documentation.

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

1
  • 1
    Ohh. I don't know how I missed it. Thanks. Aug 1, 2019 at 5:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.