Start learning free

LESSON 67 OF 71 · PROJECTS: OBJECT-ORIENTED

Stack in Swift: Build a MyStack Class

Practice Read the full explanation

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a private var data = [Int]() array and offers four operations.

The methods:

  • func push(_ value: Int)
  • func pop() -> Int
  • func peek() -> Int
  • func size() -> Int

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In Swift, removeLast() and last! on an empty array crash the program.)

You start with: The starter already contains the code that uses your stack (below).

let stack = MyStack()
stack.push(10)
stack.push(20)
stack.push(30)
print("Top: \(stack.peek())")
print("Size: \(stack.size())")
print("Pop: \(stack.pop())")
print("Size: \(stack.size())")
print("Pop: \(stack.pop())")
print("Pop: \(stack.pop())")
print("Empty size: \(stack.size())")
stack.push(7)
print("Top: \(stack.peek())")
print("Size: \(stack.size())")

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

Arrays have append, removeLast() (which removes and returns the last element) and last (an optional, so write data.last!).

class MyStack {
    private var data = [Int]()

    func push(_ value: Int) {
        data.append(value)
    }

    func pop() -> Int {
        return data.removeLast()
    }

    func peek() -> Int {
        return data.last!
    }

    func size() -> Int {
        return data.count
    }
}

STEP 1 OF 10
    Ctrl + Enter to check

    SWIFT · PROJECTS: OBJECT-ORIENTED

    Stack Impl in Swift, explained

    Problem overview

    A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is called LIFO, last in, first out. Think of a pile of plates: you add to the top and take from the top.

    The lesson asks for a class MyStack that stores whole numbers in a private var data = [Int]() array and offers four operations:

    • push(_ value: Int) puts a value on top and returns nothing.
    • pop() -> Int removes the top value and returns it.
    • peek() -> Int returns the top value but leaves it on the stack.
    • size() -> Int returns how many values are on the stack.

    The driver pushes 10, 20 and 30, then peeks, pops everything, and finally pushes 7 onto the emptied stack. The output is:

    Top: 30
    Size: 3
    Pop: 30
    Size: 2
    Pop: 20
    Pop: 10
    Empty size: 0
    Top: 7
    Size: 1
    

    Pops come out as 30, 20, 10, the reverse of the order they went in. After the last pop the size is 0, and the stack keeps working: the push of 7 gives a top of 7 and a size of 1.

    Approach: the end of the array is the top

    The array does the storage, and the only decision is which end of it is the top of the stack. Choose the end. Adding and removing at the end of a Swift array is cheap, and the most recently pushed value is always the last element. If the top were the front, every push and pop would have to shift all the other elements.

    With that choice, each operation is a single array call: append for push, removeLast() for pop, last for peek and count for size.

    Step by step

    1. Declare the class and write its closing brace immediately. The driver's MyStack() builds an object from it.
    2. Add the storage: private var data = [Int](). It is var because the array changes, and private because outside code should go through the four methods and never touch the array.
    3. Start push. Swift normally makes callers write a parameter's name, but the underscore before value turns that off, so the driver can write stack.push(10).
    4. Append the value to the end of data.
    5. Start pop, which returns an Int.
    6. Return data.removeLast(). That one call removes the last element and hands it back, so the stack shrinks and the caller gets the value.
    7. Start peek, also returning an Int.
    8. Return data.last!. The property last is an optional, because an empty array has no last element. The ! unwraps it, asserting that a value is there.
    9. Start size with an Int result.
    10. Return data.count, one array element per stacked value.

    The solution in Swift

    class MyStack {
        private var data = [Int]()
    
        func push(_ value: Int) {
            data.append(value)
        }
    
        func pop() -> Int {
            return data.removeLast()
        }
    
        func peek() -> Int {
            return data.last!
        }
    
        func size() -> Int {
            return data.count
        }
    }
    
    class Solution {
        func mainFunction() {
            let stack = MyStack()
            stack.push(10)
            stack.push(20)
            stack.push(30)
            print("Top: \(stack.peek())")
            print("Size: \(stack.size())")
            print("Pop: \(stack.pop())")
            print("Size: \(stack.size())")
            print("Pop: \(stack.pop())")
            print("Pop: \(stack.pop())")
            print("Empty size: \(stack.size())")
            stack.push(7)
            print("Top: \(stack.peek())")
            print("Size: \(stack.size())")
        }
    }
    

    Details worth knowing

    • pop versus peek. Both give back the top value, but removeLast() changes the array and last only reads it. Calling peek() twice gives the same answer and leaves the size alone. For a stack holding 1 and 2, peek() twice and then size() prints 2 2 2.
    • Why last is optional. Swift makes you handle the case of an empty array. The lesson's ! says "I know there is a value". It is safe here because the tests never peek at an empty stack.
    • Why removeLast() is not optional. The array method popLast() returns an optional, but removeLast() returns the element itself and requires the array not to be empty.
    • Private storage. Because data is private, nobody can reorder or remove from the middle of the pile, which would break the rule that only the top is accessible.

    Complexity

    Every operation takes constant time. append is amortized O(1): occasionally the array has to grow, but averaged over many pushes the cost per push is constant. removeLast(), last and count are all O(1). The stack uses O(n) space for the n values it currently holds.

    Edge cases and common mistakes

    • Popping or peeking an empty stack. The tests never do it, but in Swift both removeLast() and last! on an empty array stop the program with a crash rather than returning a value. A real stack would usually check size() first or return an optional.
    • Using the front as the top. removeFirst() would return the oldest value, which makes a queue, not a stack. The driver's output would then read 10, 20, 30 instead of 30, 20, 10.
    • Changing the size in peek. If peek used removeLast(), the driver's second Size: 3 would be wrong, and later pops would return the wrong values.
    • Forgetting the underscore in push. Without it, callers must write push(value: 10), and the driver's push(10) does not compile.
    • Reusing after empty. There is no state to reset when the stack empties. The array is just empty, and the next append works as usual.

    Testing

    Two more checks with the same class:

    let other = MyStack()
    other.push(1)
    other.push(2)
    print(other.peek(), other.peek(), other.size())
    
    2 2 2
    

    After pop() removes the 2, a peek() gives 1 and size() gives 1. A freshly created stack has size() 0 before any push.

    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free