Swift Enums

Swift: Enums

An enum is a data type that has a finite set of possible values. In this post we discuss will the most important aspects of enums in Swift.

Hint: This post has been updated to Swift 3

Declaration

The declaration of an enum is very straightforward in Swift. You do it with the  enum keyword:

Alternatively, you can combine cases, which doesn’t make any difference at all at this basic setup:

Now you can declare a variable of this type and assign one of the TestEnum’s values:

Raw Values

It possible for an enum to have associcated default values, in Swift called raw values. If an enum has raw values, they must be all of the same type and every possible value has to have a raw value. Let’s take a look at an example:

In this example, the type for the raw values is integer. Then all values get a raw value assigned. If an enum has raw values, you can easily access them by the property  rawValue:

Associated Values

It is also possible that at initialization time a value can be associated with the enum. For that, you need to declare what type each associated value is of:

To access the associated value, you need to make use of a switch:

Unfortunately, it is not possible to access the associated value directly. But you can make it much more convent by using a function inside of the enum.

Properties and functions

One very interesting feature of enums is, that they can also implement functions and properties. So it is possible for example to declare a function that returns the associated value:

Indirect Enums

Since Swift 2.0 there are so called indirect enums. In the Xcode release notes there’s the following explanation:

Enums and cases can be marked indirect, which causes the associated value for the enum to be stored indirectly, allowing for recursive data structures to be defined.

So now enums can be recursive, that means you can for example build a tree with enums. Let’s take a look at an example:

For a enum to be indirect, we must use the keyword  indirect in front of the enum.  Now let’s create a tree:

It looks like this:

Bildschirmfoto 2015-08-04 um 11.57.54Now we can create a function that goes recursively through the tree and adds up all numbers:

The printed result is 21.

Conclusion

Enums are a very important language feature in Swift. They have all the standard functionality you know from other programming languages. In addition, there are also some very useful advanced features like adding properties and functions, indirect enums and enums with associated values.

References

Swift Programming Series (iBook Store)
Image: @ Ivan Ryabokon / Shutterstock.com

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon