Last active
July 11, 2019 19:08
-
-
Save yoichitgy/30610aedd59babd70a848a9660164c75 to your computer and use it in GitHub Desktop.
Simple DI Container in Swift (Demo at iOSCon 2017 in London)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Demo at iOSCon 2017 in London | |
// https://speakerdeck.com/yoichitgy/dependency-injection-in-practice-ioscon | |
// | |
// How to Use: Paste this program to a Playground. | |
// Tested with: Xcode 8.2.1 | |
protocol Animal: class { } | |
class Cat: Animal { } | |
class Dog: Animal { } | |
class PetOwner { | |
let pet: Animal // Depends on protocol | |
init(pet: Animal) { | |
self.pet = pet | |
} | |
} | |
class Container { | |
var factories = [String: Any]() | |
func register<T>(_ type: T.Type, factory: @escaping () -> T) { | |
let key = String(reflecting: type) | |
factories[key] = factory as Any | |
} | |
func resolve<T>(_ type: T.Type) -> T? { | |
let key = String(reflecting: type) | |
guard let factory = factories[key] as? () -> T else { | |
return nil | |
} | |
return factory() | |
} | |
} | |
// At program entry point | |
let container = Container() | |
do { | |
let cat = Cat() | |
container.register(Animal.self) { cat } | |
container.register(PetOwner.self) { | |
PetOwner(pet: container.resolve(Animal.self)!) | |
} | |
} | |
// Anywhere later | |
let pet = container.resolve(Animal.self) | |
pet is Cat | |
let yoichi = container.resolve(PetOwner.self)! | |
yoichi.pet is Cat | |
let anya = container.resolve(PetOwner.self)! | |
anya !== yoichi | |
anya.pet === yoichi.pet | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment