Tree
A hierarchical tree structure for Swift
I’m pleased to announce the release of an open source package for Swift called Tree.
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, and 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"))
}
The full documentation is available here: Documentation.