Advanced and Practical Enum usage in Swift

Linked Lists

released Fri, 01 Mar 2019
Swift Version 5.0

Linked Lists

Airspeed Velocity has a great writeup on how to implement a Linked List with an enum. Most of the code in his post goes far beyond enums and touches a lot of interesting topics 1, but the basis of his linked list looks kinda like this (I simplified it a bit):

enum List {

     case end

     indirect case node(Int, next: List)


Each node case points to the next case, and by using an enum instead of something else, you don't have to use an optional for the next value to signify the termination of the list.

Airspeed Velocity also wrote a great post about the implementation of a red black tree with indirect Swift enums, so while you're already reading his blog, you may just as well also read this one.