In the previous exercise, the function printAllNodes()
visited each of the Node
s in the ice cream sequence in an iterative manner, repeatedly setting and then re-setting the value assigned to unwrappedNode
. In this exercise, we’ll create a function that also visits each of the Node
s in the ice cream sequence but does so in a different way: recursively.
Instructions
First, define a function called printAllNodesRecursively()
with an argument label of startingAt
and a parameter of node
with an optional type of Node
. Leave the body empty.
Let’s start to create the logic needed in our recursive function to visit all the nodes.
Create a constant called node
and set it as node
, the argument passed into the function.
Here, the printAllNodesRecursively()
function should exit with the return
keyword when it is passed a node
that is nil
. (Remember that if you’ve reached a node
that is nil
in the sequence of Node
s it indicates that there are no Node
s left to visit.)
Change your code declaring the variable node
to use a guard
statement that checks if the node has a value, and if it is nil
, exits from the function with a return
.
If the node
has a value, you’ll want to print that node
s data. Add this logic on a new line under the guard
statement.
Lastly, a recursive function is defined as a function that calls itself. Below the line where you printed node
‘s data
, call printAllNodesRecursively()
with the next Node
as the argument.
Test your function. Outside of printAllNodesRecursively()
, call it with the first Node
in the ice cream sequence, strawberry
. You should see all the ice cream flavors print in the terminal.