Clicky

iOS Dev Nugget 202 Swift Enumerations to Encode States

.

Need to run a code review on your codebase? Hire me

Swift Enumerations with associated values are useful for representing a constrained set of cases with associated values. For e.g. in #193, I talked about using Result Enumerations to simplify error handling. In that example, there are 2 possible cases/states — Success and Failure.

In a similar manner, you can use enum cases to encode values such that you can simplify code and reduce duplication by eliminating nil handling. A good example is when you are building a tree or a linked list. There is often a Node type that looks like this for singly linked lists:

class Node<T> {
    var next: Node<T>?
    var value: T?
}

Or for binary trees:

class Node<T> {
    var left: Node<T>?
    var right: Node<T>?
    var value: T?
}

While you can rely on optionals, it gets unwieldly as you need to do nil checks for each var that is an optional Node.

Using enums, you can instead do:

indirect enum Node<T> {
    case Node(value: T)
    case Empty
}

A good example of this approach for working with Binary trees can be found at The power of Swift enums. Look under the title Binary trees.

Enums are shaping up to be a very useful construct in Swift.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues