Skip to content

Instantly share code, notes, and snippets.

@derrh
Created December 13, 2016 06:06
Show Gist options
  • Save derrh/c97b261e793845b10b1a584f205b2d8e to your computer and use it in GitHub Desktop.
Save derrh/c97b261e793845b10b1a584f205b2d8e to your computer and use it in GitHub Desktop.
Polymorphism with Swift Value Types: Mind Blown
protocol Thing {
func foo()
}
extension Thing {
func foo() {
print("just a thing")
}
}
struct Sprocket: Thing {
func foo() {
print("sprocket")
}
}
struct Widget: Thing {
func foo() {
print("widget")
}
}
enum Instrument: Thing {
case trombone
func foo() {
print("not even a struct!?")
}
}
extension Int: Thing {
func foo() {
print("now you're trolling me!!!")
}
}
struct Boring: Thing {
}
let things: [Thing] = [Sprocket(), Widget(), Boring(), Instrument.trombone, 12]
things.forEach { $0.foo() }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment