Stack implementation is now complete. We can
peek values on the
Stack. As we know if we attempt too many
nil is returned as there are no
Nodes on the stack.
However, what happens if we keep adding nodes onto the
Stack? There is nothing limiting the size of the stack! As we know with dishes, if the pile of dishes gets too high we may have a crash! This is the same for us,
Stacks take up memory and in many cases, we will want a limit on the size.
In this exercise, we will extend our
Stack class to have the concept of maximum size.
We need to set the maximum size of the
First, let’s create a private var property called
size in our
Stack struct and set the initial value to 0.
Next, we will add private var property called
maxSize which we will initialize in the
init() function. Set the
type of this to be
With structs, all properties need to be initialized inline where the property is declared as
size was or we need to initialize it in the
Create an initializer and pass in a
maxSize parameter of type
For our exercise let’s set the default value to 2.
Initializers have the format
init(<variable name>:<type> = <default value>)
Be sure to save the
maxSize parameter into the
Now that we have
maxSize properties we can add these into
push() add a guard statement in the first line of the method to check that
size < maxSize. If the else is invoked we want to print out
The stack is full! No room to add \(str) and return.
If we do not enter the else, we know we will be adding on to the stack. In this case, increment the
size property by 1 before we call
pop() we already have a
guard statement allowing us confidence that there is a
node that has been removed. We simply need to add a decrement of
size by 1 before we return
Give it a try! In this case our defensive code should only allow two plates on the stack!