Enums in Swift
How to properly use enum effectively to model your data
Enumerations — usually just called “enum” — are a way to define your own kind of value in Swift. In enum you can organize groups of values that are related.
Enum Syntax:-
Switch Statement using enums:-
Iterating over all enum cases:-
CaseIterable
protocol helps to iterating over all enum cases and gives total amount of cases. At compile time, Swift will automatically create an allCases
property that is an array of all your enum cases.
Enum and Equatable:-
Equatable protocol helps to compare enum
Enums with Values:-
Till now we discussed on what is enum and it’s syntax. Now it’s time to discuss can enum holds value? yes enum can hold values.
User-defined
Enum case cannot have a raw value if the enum does not have a raw type.
You could use the enum with defined values if enum is having a raw type:
In the above example, enum rawType is string so by default it take case name as rawvalue.
We can explicitly provide the raw value to enum as:-
Initializing from a Raw Value:-
You can initialise enum using raw value as follows:
Enum with Associated Values:-
Each enum can be paired with it’s own data is called as associated type
Enums with methods:-
You can define methods inside enum.
Enum with Protocols:
enum can adopt protocols.
Enums can have methods, subscripts, and computed properties. But it cannot have stored properties.
If you enjoyed reading this post, please share and give some clapps so others can find it 👏👏👏👏👏 !!!!
You can follow me on Medium for fresh articles.