Stack

OVERVIEW

Stack is like an array but it has limited functionality which only limits you to push and pop element into your stack. With push, you add a new element on top of the array while pop remove the element from the top and returns the first element of the stack.

Do take note that this only work with Int given the type being used here. If you would like to use extend it to allow all type, you may use generic in this case.

A stack is also a LIFO or last-in-first-out order. The element being pushed last is the first one to come off in the next pop.

public struct Stack {
    var array = [Int]()

    mutating func push(_ number: Int) {
        array.append(number)
    }

    mutating func pop() -> Int? {
        return array.popLast()
    }
}

var stack = Stack(array: [1, 2, 3, 4])
stack.push(10)
print(stack.array)
// [1, 2, 3, 4, 10]

stack.pop()
print(stack.array)
// [1, 2, 3, 4]

stack.pop()
print(stack.array)
// [1, 2, 3]

stack.pop()
print(stack.array)
// [1, 2]

stack.push(15)
print(stack.array)
// [1, 2, 15]

 

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

  • What is inheritance?

    Definition: allow derived classes to share interfaces and codes of their base classes By using inheritance, there are two things that […]

  • iOS Tutorials: Localize your app with a button click

    OVERVIEW Localization expands your app coverage to people from different part of the world. Although English is an international language, […]

  • What is nil coalescing?

    Nil-Coalescing is like an else in if statement. It allows you to check if there is a value, and if there […]

  • 2017 Top App Downloads

    As an mobile developer, it is always good to learn from other popular apps on what they have done to […]

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*