Skip to content

Posts from the ‘Swift’ Category

18
Jul

Example: Implement a Stack of Strings in Swift

Next example show how to implement a stack of strings in Swift.

StackOfStrings.swift file

import Foundation
 
class StackOfStrings:NSObject {
 
    class Element: NSObject {
        var value: String = ""
        var next:Element? = nil
    }
 
    var topElement:Element = Element()
 
    func isEmpty() -> Bool {
        return topElement == nil
    }
 
    func push(var elem:String) {
        var oldTopElement = topElement
        topElement = Element()
        topElement.value = elem
        topElement.next = oldTopElement
    }
 
    func pop() -> (elem:String) {
        var value: String = topElement.value
        topElement = topElement.next!
        return value
    }
}

Read more »