✅ Swift Stack Using Array

Here’s a simple and clean implementation of a Stack using an Array in Swift, including basic operations:

struct Stack<T> {
private var elements: [T] = []

// Push an element onto the stack
mutating func push(_ value: T) {
e…


This content originally appeared on DEV Community and was authored by Harsh Prajapat

Here's a simple and clean implementation of a Stack using an Array in Swift, including basic operations:

struct Stack<T> {
    private var elements: [T] = []

    // Push an element onto the stack
    mutating func push(_ value: T) {
        elements.append(value)
    }

    // Pop an element from the top of the stack
    mutating func pop() -> T? {
        return elements.popLast()
    }

    // Peek at the top element without removing it
    func peek() -> T? {
        return elements.last
    }

    // Check if the stack is empty
    func isEmpty() -> Bool {
        return elements.isEmpty
    }

    // Get the current size of the stack
    func size() -> Int {
        return elements.count
    }
}

🧪 Example Usage:

var stack = Stack<Int>()

stack.push(10)
stack.push(20)
stack.push(30)

print(stack.peek() ?? "Empty")  // Output: 30
print(stack.pop() ?? "Empty")   // Output: 30
print(stack.size())             // Output: 2
print(stack.isEmpty())          // Output: false

stack.pop()
stack.pop()
print(stack.isEmpty())          // Output: true


This content originally appeared on DEV Community and was authored by Harsh Prajapat


Print Share Comment Cite Upload Translate Updates
APA

Harsh Prajapat | Sciencx (2025-07-14T17:13:05+00:00) ✅ Swift Stack Using Array. Retrieved from https://www.scien.cx/2025/07/14/%e2%9c%85-swift-stack-using-array/

MLA
" » ✅ Swift Stack Using Array." Harsh Prajapat | Sciencx - Monday July 14, 2025, https://www.scien.cx/2025/07/14/%e2%9c%85-swift-stack-using-array/
HARVARD
Harsh Prajapat | Sciencx Monday July 14, 2025 » ✅ Swift Stack Using Array., viewed ,<https://www.scien.cx/2025/07/14/%e2%9c%85-swift-stack-using-array/>
VANCOUVER
Harsh Prajapat | Sciencx - » ✅ Swift Stack Using Array. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/07/14/%e2%9c%85-swift-stack-using-array/
CHICAGO
" » ✅ Swift Stack Using Array." Harsh Prajapat | Sciencx - Accessed . https://www.scien.cx/2025/07/14/%e2%9c%85-swift-stack-using-array/
IEEE
" » ✅ Swift Stack Using Array." Harsh Prajapat | Sciencx [Online]. Available: https://www.scien.cx/2025/07/14/%e2%9c%85-swift-stack-using-array/. [Accessed: ]
rf:citation
» ✅ Swift Stack Using Array | Harsh Prajapat | Sciencx | https://www.scien.cx/2025/07/14/%e2%9c%85-swift-stack-using-array/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.