Protocols associated type in Swift
Forums:
protocol Stack {
typealias ItemType
func push(item: ItemType)
func pop() -> ItemType
var topItem: ItemType {get}
}
class IntStack: Stack {
private var items = [Int]()
func push(item: Int) {
items.append(item)
}
//without range checking
func pop() -> Int {
return items.removeLast()
}
var topItem: Int {
return items[items.count - 1]
}
}
let stack = IntStack()
stack.push(1)
stack.push(2)
var topItem = stack.pop()
//topItem is 2
topItem = stack.topItem
//topItem is 1
- Log in to post comments