Skip to content

Instantly share code, notes, and snippets.

@designatednerd
Created July 3, 2019 14:27
Show Gist options
  • Save designatednerd/a3d5033a43ad9ac1fb3125b4589a7cfc to your computer and use it in GitHub Desktop.
Save designatednerd/a3d5033a43ad9ac1fb3125b4589a7cfc to your computer and use it in GitHub Desktop.
Composing A Protocol
protocol BaseDelegate: class {
func baseMethod()
}
protocol SecondaryDelegate: BaseDelegate {
func secondaryMethod()
}
protocol TertiaryDelegate: BaseDelegate {
func tertiaryMethod()
}
class SomethingWithDelegate {
var baseDelegate: BaseDelegate
init(baseDelegate: BaseDelegate) {
self.baseDelegate = baseDelegate
}
func runTheMethods() {
self.baseDelegate.baseMethod()
if let secondary = self.baseDelegate as? SecondaryDelegate {
secondary.secondaryMethod()
}
if let tertiary = self.baseDelegate as? TertiaryDelegate {
tertiary.tertiaryMethod()
}
}
}
class ConformsToBase: BaseDelegate {
func baseMethod() {
print("I only conform to the base method")
}
}
class ConformsToSecondary: SecondaryDelegate {
func secondaryMethod() {
print("I conform to secondary as well!")
}
func baseMethod() {
print("I conform to base and...")
}
}
class ConformsToTertiary: TertiaryDelegate {
func baseMethod() {
print("I conform to base and...")
}
func tertiaryMethod() {
print("I conform to tertiary as well!")
}
}
class ConformsToAll: SecondaryDelegate, TertiaryDelegate {
func baseMethod() {
print("I conform to base and...")
}
func secondaryMethod() {
print("I also conform to secondary and...")
}
func tertiaryMethod() {
print("I also conform to tertiary!")
}
}
let thing1 = SomethingWithDelegate(baseDelegate: ConformsToBase())
print("=== THING 1 ===")
thing1.runTheMethods()
let thing2 = SomethingWithDelegate(baseDelegate: ConformsToSecondary())
print("=== THING 2 ===")
thing2.runTheMethods()
let thing3 = SomethingWithDelegate(baseDelegate: ConformsToTertiary())
print("=== THING 3 ===")
thing3.runTheMethods()
let thing4 = SomethingWithDelegate(baseDelegate: ConformsToAll())
print("=== THING 4 ===")
thing4.runTheMethods()
=== THING 1 ===
I only conform to the base method
=== THING 2 ===
I conform to base and...
I conform to secondary as well!
=== THING 3 ===
I conform to base and...
I conform to tertiary as well!
=== THING 4 ===
I conform to base and...
I also conform to secondary and...
I also conform to tertiary!
@designatednerd
Copy link
Author

I was pretty convinced this was not possible without @objc but I am happy to be proven wrong!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment