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"
}
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.
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).
enum s do have stored type properties - i.e., static properties. They don't have stored instance properties.
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.
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.
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