Associated Type Protocol in Swift
Level 5549 keystrokes
Container declares an associatedtype Item that each conforming type chooses. The generic Stack<Element> conforms, and Swift infers Item = Element from its methods. With two strings pushed, it prints Count: 2, First: Swift and Popped: Rocks.
Swift code
1protocol Container { // Placeholder type chosen by each conforming type2 associatedtype Item // Requirements written in terms of Item3 var count: Int { get }4 mutating func append(_ item: Item)5 subscript(i: Int) -> Item { get }6}7 // Generic stack; Item is inferred as Element8struct Stack<Element>: Container {9 var items: [Element] = [] // Satisfies count with a computed property10 var count: Int { items.count } // mutating because it changes items11 mutating func append(_ item: Element) { items.append(item) }12 subscript(i: Int) -> Element { items[i] } // Extra method not in the protocol: removes and returns the last item, or nil13 mutating func pop() -> Element? { items.popLast() }14}15 // Element is String for this stack16var stack = Stack<String>()17stack.append("Swift")18stack.append("Rocks")// Prints Count: 2, First: Swift19print("Count: \(stack.count), First: \(stack[0])")// pop() removes the last item: prints Popped: Rocks20print("Popped: \(stack.pop() ?? "nil")")Output
Count: 2, First: Swift Popped: Rocks
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Swift code and how often they appear.
(× 16)× 16:× 11"× 10{× 8}× 8.× 7>× 5[× 4]× 4