Protocol Composition in Swift

protocol CanDoDogThings {

func bark()

func waggTail()

}
struct Runner {

let dog: CanDoDogThings

func ballFound() {
dog.waggTail()
dog.bark()
}

}
protocol CanBark {
func bark()
}
protocol CanWaggTail {
func waggTail()
}
struct Dog {

// Protocol Composition
typealias Dependency = CanBark & CanWaggTail

let dogManager: Dependency

func ballFound() {
dogManager.waggTail()
dogManager.bark()
}

}
/*----- Another Way! -----*/// Protocol Composition
protocol CanDoDogThings: CanBark, CanWaggTail {

}
struct Dog {

let dogManager: CanDoDogThings

func ballFound() {
dogManager.waggTail()
dogManager.bark()
}
}
  • All the dependencies are now clearly defined.
  • Single top level entry point to rule them all 😅.
  • The compiler can enforce that the full protocol has been implemented.
  • It overall feels cleaner and cohesive.

A Software Engineer with a passion for technology. Working as an iOS Developer @BBC

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Melvin John

Melvin John

A Software Engineer with a passion for technology. Working as an iOS Developer @BBC

More from Medium

Maegan’s Weekly Stream Links — Issue #3

I finally used method-swizzling

Xcode-How to change the main Storyboard

RxSwift Combination Operators: zip, combineLatest & withLatestFrom