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:-

enum Syntax
simple example of enum

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.

enum without raw value

You could use the enum with defined values if enum is having a raw type:

prints black

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:-

prints 100 and automatically increment value by 1 to other cases

Initializing from a Raw Value:-

You can initialise enum using raw value as follows:

prints 100

Enum with Associated Values:-

Each enum can be paired with it’s own data is called as associated type

prints “hi”

Enums with methods:-

You can define methods inside enum.

prints 101

Enum with Protocols:

enum can adopt protocols.

prints black

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.

iOS Developer in walmart