Skip to content

Instantly share code, notes, and snippets.

@JarvisTheAvenger
Created August 7, 2021 08:15
Show Gist options
  • Save JarvisTheAvenger/504cb82ff1bd460b6c0ae2440bf175b2 to your computer and use it in GitHub Desktop.
Save JarvisTheAvenger/504cb82ff1bd460b6c0ae2440bf175b2 to your computer and use it in GitHub Desktop.
import Foundation
// Dependency Injection
/*
Dependency Injection is often used with the intention of writing code that is loosely coupled, and thus, easier to test.
Types of dependecy injection:
1. Property Injection
2. Constructor Injection
3. Interface Injection
*/
// 1. Property Injection
struct Profession {
var name : String
}
// This involves tight coupling and creating it's own dependency
struct George {
var profession = Profession(name: "Engineer") // This is tight coupling
var subProfession : Profession?
}
var user = George()
user.subProfession = Profession(name: "Tester") // This is property injection
//2. Constructor Injection
struct Tony {
var profession : Profession
init(_ profession: Profession) {
self.profession = profession
}
}
let tony = Tony(Profession(name: "Doctor"))
//3. Interface Injection
protocol Dependency {}
protocol HasDependency {
func setDependency(_ dependency: Dependency)
}
protocol DoesSomething {
func doSomething()
}
class Client: HasDependency, DoesSomething {
private var dependency: Dependency!
func setDependency(_ dependency: Dependency) {
self.dependency = dependency
}
func doSomething() {
// Does something with a dependency
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment