Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active June 8, 2020 15:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ha1f/cc47dafd425fc91464a4445ad034da52 to your computer and use it in GitHub Desktop.
Save ha1f/cc47dafd425fc91464a4445ad034da52 to your computer and use it in GitHub Desktop.
import Foundation
protocol Alphabet {
func accept(_ visitor: AlphabetVisitor)
}
class A {
let aProperty = "A"
}
extension A: Alphabet {
func accept(_ visitor: AlphabetVisitor) {
visitor.visitA(self)
}
}
class B {
let bProperty = "B"
}
extension B: Alphabet {
func accept(_ visitor: AlphabetVisitor) {
visitor.visitB(self)
}
}
class AlphabetSet {
var alphabets: [Alphabet]
init(_ alphabets: [Alphabet] = []) {
self.alphabets = alphabets
}
}
extension AlphabetSet: Alphabet {
func accept(_ visitor: AlphabetVisitor) {
alphabets.forEach {
$0.accept(visitor)
}
}
}
class AlphabetVisitor {
func visitA(_ object: A) {
print(object.aProperty)
}
func visitB(_ object: B) {
print(object.bProperty)
}
}
AlphabetSet([A(), AlphabetSet([A(), B(), A(), A(), B()]), A()]).accept(AlphabetVisitor())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment