A small library to convert a tree structure into a String
, designed to be used for debugging purposes.
- Include the framework in your project
- Conform your type to be
TreeRepresentable
let treeString = TreePrinter.printTree(root: rootNodeOfYourTree)
Say you already have some structure that represents a tree:
struct SomeTreeStructure {
let title: String
let childNodes: [SomeTreeStructure]
}
You start by confirming your type to TreeRepresentable
:
extension SomeTreeStructure: TreeRepresentable {
var name: String { return self.title }
var subnodes: [SomeTreeStructure] { return self.childNodes }
}
Then, you can easily debug a tree as such:
func someFunctionYoureTesting() {
var treeRoot: SomeTreeStructure = /* Your tree */
print(TreePrinter.printTree(root: treeRoot))
}
By default, for the tree that is used for the purposes of unit testing, the result will be:
Root
├── Branch Depth One A
│ ├── Branch Depth Two A
│ ├── Branch Depth Two B
│ │ └── Leaf Depth Three
│ └── Branch Depth Two C
└── Branch Depth One B
TreePrinter
will use a sensible set of default options, however, many things are customizable:
spacesPerDepth
— Amount of indentation; defaults to4
.spacer
— Actual spacer; defaults toverticalLine
— Vertical line; defaults to│
intermediateConnector
— Connects a node that is not the leaf to the node above it; defaults to├
finalConnector
— Connects a leaf node to the node above it; defaults to└
connectorSuffix
— Suffix after the connector; defaults to──
To customize any part of the tree print, create an instance of TreePrinter.TreePrinterOptions
and
pass alternates for any of the above. The rest, if not provided, will use the default values. Then print the tree
as such:
TreePrinter.printTree(root: treeRoot, options: treePrinterOptions)
- In Xcode 11+,
File
→Swift Packages
→Add Package Dependency
- Add the URL for this repository:
https://github.com/cliss/TreePrinter.git
- Make copies of
Sources/TreePrinter/TreeRepresentable.swift
andSources/TreePrinter/TreePrinter.swift
- Add them to your project