Skip to content

Instantly share code, notes, and snippets.

@marianolatorre
Created August 15, 2016 20:14
Show Gist options
  • Save marianolatorre/ebb0c552661f90a642e26e49f064e386 to your computer and use it in GitHub Desktop.
Save marianolatorre/ebb0c552661f90a642e26e49f064e386 to your computer and use it in GitHub Desktop.
struct IntStack {
var items = [Int]()
mutating func push(item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
}
//
// using generics instead of Int:
//
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
// using it:
var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
stackOfStrings.push("cuatro")
//
// extending a generic type
//
extension Stack {
var topItem: T? {
return items.isEmpty ? nil : items[items.count - 1]
}
}
if let topItem = stackOfStrings.topItem {
print(topItem)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment