Created
August 15, 2016 20:14
-
-
Save marianolatorre/ebb0c552661f90a642e26e49f064e386 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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