Dependency Injection — What is It, and How to Use It.

What is a Dependency?

Using Dependencies in Code

class Colony {
var queen: Bee
init() {
queen = QueenBee()
}
func formColony() {
queen.startMating()
}
}
class QueenBee: Bee {
func startMating() {
print("Begin mating flight.")
}
}
protocol Bee {
func startMating()
}

Dependency Injection Using Swift

Initializer Injection

class Colony {
var queen: Bee
init(queen: Bee) {
self.queen = queen
}
func formColony() {
queen.startMating()
}
}
let firstQueen = QueenBee()let firstColony = Colony(queen: firstQueen)
firstColony.formColony()
class Colony {
var queen: Bee
init(queen: Bee, hiveType: Hive) {
self.queen = queen
}
func formColony() {
queen.startMating()
}
}
let firstQueen = QueenBee()
let topBar = TopBarHive()
let firstColony = Colony(queen: firstQueen, hiveType: topBar)

Property Injection

class Colony {
var queen: Bee!

func formColony() {
queen.startMating()
}
}
let firstQueen = QueenBee()let firstColony = Colony()
firstColony.queen = firstQueen
firstColony.queen.startMating()

Method Injection

class Colony {
var queen: Bee!

func formColony() {
queen.startMating()
}

func setQueenBee(_ queen: Bee) {
self.queen = queen
}
}
let firstQueen = QueenBee()let firstColony = Colony()
firstColony.setQueenBee(firstQueen)

Conclusion

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