Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,847 questions

51,768 answers

573 users

How to implement a stack using struct in Swift

1 Answer

0 votes
struct Stack<T> {
    private var items: [T] = []

    mutating func push(_ item: T) {
        items.append(item)
    }

    mutating func pop() -> T? {
        return items.popLast()
    }

    func peek() -> T? {
        return items.last
    }

    var isEmpty: Bool {
        return items.isEmpty
    }

    var count: Int {
        return items.count
    }
    
    func printStack() {
        print("Current Stack (top to bottom):")
        for item in items.reversed() {
            print(item)
        }
    }
}

var stringStack = Stack<String>()

stringStack.push("Swift")
stringStack.push("C")
stringStack.push("C++")
stringStack.push("Java")

print("Top: \(stringStack.peek() ?? "Empty")")

print("Popped: \(stringStack.pop() ?? "Empty")")

stringStack.printStack()



/*
run:

Top: Java
Popped: Java
Current Stack (top to bottom):
C++
C
Swift

*/

 



answered Aug 16, 2025 by avibootz
...