24

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

27

Yes, according to the documentation.

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ohh. I don't know how I missed it. Thanks.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.