As a printf debugger, I have a little trick I like to use when logging hierarchy function calls. For example:
struct Node {
var name: String
var children = [Node]()
init(_ name: String) {
self.name = name
}
mutating func addChild(child: Node) {
children.append(child)
}
func printHierarchy() {
print("\(name)")
for each in children {
each.printHierarchy()
}
}
}
var root = Node("Topmost")
var n1 = Node("n1")
var n2 = Node("n2")
var n3 = Node("n3")
var n4 = Node("n4")
n3.addChild(child: n4)
n2.addChild(child: n3)
root.addChild(child: n1)
root.addChild(child: n2)
root.printHierarchy()
This prints:
Topmost
n1
n2
n3
n4
which isn't that useful. But if we modify printHierarchy()
to add an indent
argument with a default value of 0:
func printHierarchy(indent: Int=0) {
print("\(String(repeating: " ", count: indent))\(name)")
for each in children {
each.printHierarchy(indent: indent + 1)
}
}
Our output becomes:
Topmost
n1
n2
n3
n4
This is especially useful when we are logging more information in each node to debug method calls up and down the hierarchy.
.
.