DAY #25

It is possible to make a linked list in 4 lines of code in Swift (but just because you can do something doesn’t mean you should)

1
2
3
4
indirect enum LinkedListNode<T> {
    case value(value: T)
    case next(value: T, next: LinkedListNode)
}
1
2
3
4
switch currentNode {
  case .value(let value): print(value)
  case .next(let value, let next): print(value); currentNode = next 
}

The “indirect” keywords signals the enum to be put into the heap instead of the stack (enums are usually inline). This means enums with the indirect keyword can be recursive.

As fun as this is, it can be a pain to remove items from this list, since the only real way is with a switch statement (or if case let).

Originally published 09/10/2021 @ https://pittcsc.org/ Discord

Published here on 09/09/2022. Blog published date reflects the original date of publication.