loading...

Swift Enumerations (Part 2)

jaumevn profile image Jaume Viñas Navas ・2 min read

In this new chapter we will cover more advanced features about Swift enumerations, remember to read the first chapter if you missed it or you want to refresh the basic concepts of Swift enums.

Associated Values

Enumeration cases have their own value and type, and sometimes it is useful to store additional data of other types alongside an enum case. Associated values are a fantastic way to achieve that by attaching custom information along with the case value, allowing this information to be different each time you use that enum case in your code.

Here’s an example of an enumeration that defines a set of actions that users can execute in order to modify a layer. A layer can be resized, rotated and filled with a color. The enum case resize has two associated values that define the new width and height values of the layer, the enum case rotate has one associated value which indicates the rotation degrees, and the enum case fill has one associated value that indicates the color of the layer.

The associated values can be accessed using a switch statement, and they can be extracted as constants (with the let prefix) or as variables (with the var prefix).

Methods

Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes, for example, instance methods to provide functionality related to the values the enumeration represents.

Methods on enumerations exist for every enum case. If you want to provide specific code for every enum case, you need a switch statement to determine each case.

Mutating Methods

By default, the properties of an enumeration cannot be modified from within its instance methods. However, if you need to modify your enumeration you can use mutating methods. Mutating methods for enumerations can set the implicit self parameter to be a different case from the same enumeration.

Here’s an example that defines an enumeration for a temperature alarm with two states, enabled and disabled. The enumeration changes its state when the temperature reaches an specific threshold.

Properties

Event though enumerations can’t have stored properties, they can have computed properties to provide additional information about the enumeration’s current value.

The example below modifies the Polygon enumeration in order to add a new property edges . This new property returns the number of edges of the enum case. The method description() has also been updated in order to use the new property.


If you find this post helpful, please recommend it for others to read. In the next chapter we will cover more advanced enumeration usages such as protocols, extensions, generics and custom initializers.

Posted on by:

Discussion

markdown guide