Blog
by Carson Katri

Cool Swift Code

4-line Linked List

You can use inderict enums to create a linked list in 4 lines:

indirect enum LinkedList<T> {
    case node(T, LinkedList)
    case end(T)
}

Combine that with a simple Sequence conformance, and you have a pretty useful LinkedList:

extension LinkedList: Sequence {
    var value: T {
        switch self {
        case .node(let val, _):
            return val
        case .end(let val):
            return val
        }
    }
    
    func makeIterator() -> LinkedList<T>.Iterator {
        Iterator(currentNode: self)
    }
    
    struct Iterator: IteratorProtocol {
        var currentNode: LinkedList<T>
        
        mutating func next() -> LinkedList<T>? {
            switch currentNode {
            case .node(_, let next):
                currentNode = next
                return next
            case .end:
                return nil
            }
        }
    }
}

It could be used like so:

let list: LinkedList<String> = .node("Hello", .node("World", .node("This", .node("is", .node("a", .end("test"))))))

var allText: String = list.value
for node in list {
    allText += " \(node.value)"
}

Coming Soon...

Generated using
Publish
and
Tokamak
RSS Feed