Tree: A hierarchical tree structure for Swift

Hi Everyone,

I thought I'd share a package that I wrote a few months ago. Compared to a lot of the packages shared here, this one is pretty simple, but it has proved quite useful in my projects.

Tree is a Swift package implementing a hierarchical tree structure constructed of interconnected nodes.

Each node has an associated value, which can be any identifiable type.

You can easily build a tree by describing the nodes in the tree. For example to create a tree of strings:

// Create a root node.
//
let root = Node("root")

// Create two nodes as children of the root node.
//
let A = root.append(child: "A")
let B = root.append(child: "B")

// Create some leaf nodes as children of node A.
//
let C = A.append(child: "C")
let D = A.append(child: "D")

You can also build the tree declaratively.

let root = Root("root") {
    Branch("A") {
        "C"
        "D"
    }
    
    "B"
}

The tree can then be iterated either using depth first, or breadth first, manipulated to append/remove/prune nodes, and the node properties can be inspected.

// Test if a node is a root node (has no parent).
//
print(root.isRoot) // "true"

// Test if a node is a leaf node (has no children).
//
print(root.isLeaf) // "false"

// Lookup a child node by identifier.
//
if let A = root.node(identifiedBy: "A") {
    // Get the parent for a node.
    //
    print(A.parent?.element) // "root"

    // Iterate over the children.
    //
    print(A.reduce("") {
        $0 + "\($1.element), "
    })
    // "C, D, "

    // Append a new child to the node.
    //
    A.append(child: Node("E"))
}

This might be useful for others, but I thought I'd share here in case it was.

The full documentation is available here: Documentation

Hope it's useful to some folks.

6 Likes