Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static let in enum instead of case

Tags:

enums

ios

swift

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"
}
like image 536
Amit Gupta Avatar asked Jul 14 '18 13:07

Amit Gupta


People also ask

Can enum have static methods Swift?

Swift's Enum can add a Static Method. You can use this to create methods that return the UI expression values ​​of all enumeration items as an array. It is the final version of the Married Enum type. Static method called strings is added to return all possible expression values as an array.

Are enum variables static?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).

Can enum have stored property?

enum s do have stored type properties - i.e., static properties. They don't have stored instance properties.

Can enums have functions Swift?

Finally, let's take a look at how enum cases relate to functions, and how Swift 5.3 brings a new feature that lets us combine protocols with enums in brand new ways. A really interesting aspect of enum cases with associated values is that they can actually be used directly as functions.


1 Answers

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.

like image 63
Milo Wielondek Avatar answered Oct 20 '22 05:10

Milo Wielondek