-
-
Save Otbivnoe/a0b4351c42b1a08f41bf0361c658ad9d to your computer and use it in GitHub Desktop.
Using protocol composition and generics for dependency injection in Interactors (VIPER, SOA, another cool keywords...)
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
protocol HasService1 { | |
var service1: Service1 { get } | |
} | |
protocol HasService2 { | |
var service2: Service2 { get } | |
} | |
class Service1 {} | |
class Service2 {} | |
//App dependencies | |
class InteractorDependencies: HasService1, HasService2 { | |
lazy var service1: Service1 = { | |
return Service1() | |
}() | |
lazy var service2: Service2 = { | |
return Service2() | |
}() | |
} | |
//Base interactor with generic for services | |
class BaseInteractor<T> { | |
typealias Dependencies = T | |
let dependencies: Dependencies | |
init(dependencies: Dependencies) { | |
self.dependencies = dependencies | |
} | |
} | |
//An example of interactor | |
class Interactor: BaseInteractor<HasService1 & HasService2> { | |
init(viewModel: String, dependencies: Dependencies) { | |
super.init(dependencies: dependencies) | |
} | |
} | |
let interactor = Interactor(viewModel: "cool", dependencies: InteractorDependencies()) | |
interactor.dependencies.service1 | |
//Inspired by: http://merowing.info/2017/04/using-protocol-compositon-for-dependency-injection/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment