Skip to content

July 18, 2014

Example: Implement a Stack of Strings in Swift

by noise

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
    }
}

main.swift file

import Foundation
 
var fileName = "test.txt"
 
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("test", ofType: "txt")
var fileError = NSErrorPointer()
let fileBuffer = NSString.stringWithContentsOfFile(path, encoding:NSASCIIStringEncoding, error:fileError) as String
 
if (fileError) {
    println("Error opening file for read")
}
 
println(fileBuffer)
 
var separator: NSCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
var arrayOfStrings: NSArray = fileBuffer.componentsSeparatedByCharactersInSet(separator)
 
var stack:StackOfStrings = StackOfStrings()
 
for word in arrayOfStrings {
 
    if word.isEqualToString("-") {
        println(stack.pop())
    } else {
       stack.push((word as String))
    }
}

You will also need a test.txt file:

the brown fox jumped - over the lazy dog - -
Read more from Swift

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments