Skip to content

Instantly share code, notes, and snippets.

@worchyld
Created October 8, 2022 02:23
Show Gist options
  • Save worchyld/0e8ed49cd62099e5056645e4f31afbf3 to your computer and use it in GitHub Desktop.
Save worchyld/0e8ed49cd62099e5056645e4f31afbf3 to your computer and use it in GitHub Desktop.
Swift deck using generics (basic)
// Generic deck management, doesn't care about its contents
protocol DeckDelegate: AnyObject {
associatedtype Element
var size: Int { get }
var isEmpty: Bool { get }
var cards:[Element] { get set }
func push(_ element: Element)
func pop() -> Element?
func shuffle()
}
class GenericDeck<Element> : DeckDelegate {
var size: Int {
return cards.count
}
var isEmpty: Bool {
return (cards.count == 0)
}
internal var cards: [Element] = []
func push(_ element: Element) {
cards.append(element)
}
func pop() -> Element? {
cards.popLast()
}
func shuffle() {
cards.shuffle()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment