Skip to content

Instantly share code, notes, and snippets.

@pitt500
Last active April 2, 2021 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pitt500/c759bd3b756b269e8c3cb8b83196ac18 to your computer and use it in GitHub Desktop.
Save pitt500/c759bd3b756b269e8c3cb8b83196ac18 to your computer and use it in GitHub Desktop.
Code made in Swift and Tips for episode "Generics in Swift: Protocols with associated types" https://youtu.be/pp4hKZBBci4
import Foundation
// MARK: - Associated Types
// Placeholder name to a type that is used as part of a protocol.
// The actual type for the associated type isn't specified until the protocol is adopted.
// Use associatedtype keyword
protocol Stack {
associatedtype Element
var count: Int { get }
mutating func push(_ element: Element)
mutating func pop() -> Element?
}
struct IntStack: Stack {
private var values: [Int] = []
var count: Int {
values.count
}
mutating func push(_ element: Int) {
values.append(element)
}
mutating func pop() -> Int? {
values.popLast()
}
}
var stack1 = IntStack()
stack1.push(1)
stack1.push(2)
stack1.push(3)
// MARK: - Generic Type using a protocol with associated type
struct MyStack<Item>: Stack {
private var values: [Item] = []
var count: Int {
values.count
}
mutating func push(_ element: Item) {
values.append(element)
}
mutating func pop() -> Item? {
values.popLast()
}
}
var stack2 = MyStack<Int>()
stack2.push(4)
stack2.push(5)
stack2.push(6)
var stack3 = MyStack<String>()
stack3.push("Hello")
stack3.push("World")
stack3.push("Everybody!")
// MARK: - Extending from a protocol with associated types
extension Array: Stack {
mutating func push(_ element: Element) {
self.append(element)
}
mutating func pop() -> Element? {
self.popLast()
}
}
// MARK: - How to solve "Protocol 'Stack' can only be used as a generic constraint ..."?
func executeOperation<Container: Stack>(container: Container) {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment