Now that we can create sequences of nodes, let’s see them in action!
Imagine we are working at an ice cream shop that sells three flavors: strawberry, banana, and coconut. The signature fruity sundae is made of these three flavors, but our new hires have a hard time remembering the order.
To help them remember, our Swift nodes may do just the trick.
Let’s get started…
You’ve been given several ice cream flavors modeled as
Node instances. Let’s go through our ice cream nodes to make sure that they are linked in the correct order.
Create a function called
printAllNodes() with an argument label of
startingAt and a parameter called
node with a type of
Node. Leave the body of the function empty for now.
printAllNodes() function will iterate through our ice cream sequence of nodes and print the data stored in each node.
printAllNodes() create a variable called
currentNode of the optional
Node type and set it’s initial value to the passed in argument,
Next, we’ll create a
while loop that only iterates when the
currentNode is not
currentNode evaluates to
nil we know that we’ve already visited all the nodes in a sequence.)
On a new line inside
printAllNodes()‘s body, create a while loop that checks a constant,
unwrappedNode, that is assigned the unwrapped value of
while loop, print the
unwrappedNode‘s data, then update
currentNode to its
printAllNodes(), call it with the argument of
strawberry passed in. You should see the ice cream flavors printed in order of
coconut in the terminal.