According to the Swift documentation enumeration is defined as “a common type for a group of related values and enables you to work with those values in a type-safe way within your code”.

The easiest way to think about enums is as structured lists of related items. A few examples:

  • Gender: Male, Female and Others
  • Designation: Mr, Miss, Mrs and Master

How to create an enum?

  1. It’s simple just follow up your enum name after the keyword enum just like we declare classes in Swift.
  2. The body of enum can include a number of cases followed by a case keyword. Cases in enum are the different values that an enum has.

Raw Values Of Enums

Enum cases can be populated with a static raw value. If we take the same example from above the code of our Gender enum will look like this:

Now the Gender enum cases contain their own raw value of datatype String. Raw values can be strings, characters, or any of the integer or floating-point number types.

How can the raw value of enum be used?

  • Getting raw value of enum case
  • Construct a value of enum

Enum initialized with initializer returns an optional enum value because enum cannot be initialized if provided with a raw value that cannot be represented by the enum.

The value of the enum case can be used in a switch like below:

Associated Values In Enums

Enums with associated values let us associate extra data with an enum case.

For this we take the next example of Ice cream Flavors as ice cream can have different numbers of scoops on its cone.

In order to make an associated value for enum just set the Data Types to receive for each case like this:

The associated value of the enum case can be used like the example below:

Bonus Tip

Enums can have its methods and properties which can be used on enum cases.

iOS Developer