So far, we’ve had to use some workarounds to visualize the tree. For example, we’ve printed the count of
children, printed its
.isEmpty status, and printed the results of our custom
== method. Wouldn’t it be nice if we could actually print the tree in a way we can see what’s in it?
To accomplish this, you’ll conform
CustomStringConvertible. Recall that this protocol has a single property,
description, that can be customized to represent your class in any way you see fit. You will build a string inside of the property and then return the completed string as the property value.
Go ahead and run the program and see how our TreeNode prints by default. Pretty useless, eh?
Let’s add the protocol conformance now!
Underneath your Equatable extension, add another extension to TreeNode, this time add the CustomStringConvertible protocol instead of the Equatable protocol, leave the extension body blank for now. Run the program again (don’t worry about the errors, we’ll fix that).
Add a single property, a
description of type String, and an empty set of curly braces (it is a computed property). Ignore the error.
description property, create a new variable,
text, and set it equal to
“Data: \(data)\n”, now
text to the
description variable. Run the program and see how our TreeNode display is coming along. You can see now that we are starting to get somewhere!
We still have pesky warning because we haven’t changed
text, we will soon, so ignore it.
Looking good, but we can do better! Let’s add a way to display how many children a TreeNode has. One the next line, before the
return statement, add:
" # of children: \(children.count)\n"
text variable. Run the program.
Next, we can display the names of the children instead of just the total number. Add logic to display the
data of the
children only if a TreeNode has
children, make sure this goes above the
return text line. We’ll leave this implementation up to you, but check out the hint if you get stuck.
Wow! Adopting one protocol made your data so much more usable! Play around with the data and change up the display to show whatever you like. When you’re finished, head on over to the next exercise.