9

I have noticed certain cases where inside an enum, instead of case people have used static let to declare variables. Is this practice justifiable?

public enum ExampleEnum {
    static let case1 = "case1"
    static let case2 = "case2"
    static let case3 = "case3"
}
2
  • 2
    Since you cannot instantite an enum without cases enums are often used as namespaces. Commented Jul 14, 2018 at 13:45
  • 1
    You may find this summary useful for understandng @HAS's point. Code like this, while potentially problematic, may also be used to support Objective-C interop. Commented Jul 14, 2018 at 14:32

1 Answer 1

4

This is a quick way of creating a namespace for constants.

You can of course achieve similar effect using a struct, however running let foo = StructOnlyForStoringConstants() will not throw an error or even a warning (can be solved using private init or even logging a warning, but we quickly lose the quick in a quick way above) and hence might be confusing (some argue). Since enums without cases (or "no-case enums") cannot be instantiated, you don't have this problem.

Another reason is that putting constants in an enum might feel more natural (than say in structs), as enums are used for storing a group of related values.

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

Comments

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.