Swift Enumerations

In this tutorial you will learn about the Swift Enumerations and its application with practical example.

Swift Enumerations

An Enumeration is a first-class data type in swift.It is consist of a set of predefined named values, called as members. Enumerations are useful when we want deal with limited set of values for variable. For example you can think of the colors of a traffic light can only be one of three colors– red, yellow or green.

Swift enumerations are much powerful yet flexible, we can access its values in a type-safe manner within your code. Enumeration values can be a string, a character, or a value of any integer or floating-point type.

Defining an enumeration

In Swift, enumeration can be declared using the enum keyword followed by a list of the individual members introduced between curly brackets {} using the case keyword.

Syntax:-

Example:-

Let’s define an enumeration for days of week –

Dot syntax

Dot syntax can be used to refer enumeration’s member if the type of an enumeration is known or can be inferred.

Example:-

Output:-

swift_enum_dot_syntax

Swift Enumeration with Switch Statement

In Swift, an enumeration can be used in switch statement as following –

Example:-

Output:-

swift_switch_with_enumeration

Swift Enumeration with Raw Values

In Swift Enumeration members can be associated with a prepopulated raw value of type Int, String, Character, etc. All of the enum member should have raw values of same type and must be unique.If integers are used for raw values, they auto-increment if no value is specified for any members.

Example:-

Output:-

swift_enum_raw_value

Swift Enumeration with Associated Values

In associated values we can store data with member of an enumeration, which changes between different instances of an enumeration. With associated values you can associate a tuple with multiple to a member of enumerations, this tuple can be of different type for each of the enumeration members.

Example:-

Output:-

swift_enum_associted_value

Iterating over Enumeration Cases

In swift, it is possible to iterate over the enumeration cases, for this we have to enable this property by adding CaseIterable after the enumeration name, then swift exposes a collection of all the cases in an allCases property of the enumeration type.Once all set, we can loop through the enum members using for-in loop as following –

Example:-

Output:-

Note:- Above Syntax must comply with the CaseIterable protocol.

Recursive Enumerations

An enumeration with another instance of the enumeration as the associated value for one or more of the enumeration is termed as recursive enumeration.A indirect keyword is used to indicate that enumeration is a recursive.

Example:-

Output:-

swift_recursive_enueration

In this tutorial we have learn about the Swift Enumerations and its application with practical example. I hope you will like this tutorial.