Dependency Injection feel like a very complicated topic but in fact it is very simple. We as devs all try to follow design principle like SOLID so that our code is properly structured in a modular way and not a spaghetti code. Dependency injection really help with this. It also helps in mocking/testing our code.
依赖注入感觉像一个非常复杂的主题,但实际上它很简单。 作为开发人员,我们都尝试遵循SOLID之类的设计原则,以便我们的代码以模块化方式(而不是意大利面条式代码)正确地进行结构化。 依赖注入确实对此有所帮助。 它还有助于模拟/测试我们的代码。
Dependency injection literally means injecting the dependency. In programming world it means injecting the dependencies our code needs in order to work. There are three flavors of dependency injection in Swift
依赖项注入从字面上意味着注入依赖项。 在编程世界中,这意味着注入代码才能正常工作。 Swift有三种类型的依赖注入
- Initializer Based 基于初始化
- Property Based 基于属性
- Parameter Based 基于参数
In this blog we will focus on Initializer Based Dependency Injection. Lets take a look at this example
在此博客中,我们将重点介绍基于初始化的依赖注入。 让我们看一下这个例子
If you look at the example above, FileUploader instance initialization is dependent on file manager and network manager. So this is a very tightly coupled code. We can use initializer based Swift Dependency Injection to make this a little better
如果查看上面的示例,则FileUploader实例的初始化取决于文件管理器和网络管理器。 因此,这是一个非常紧密耦合的代码。 我们可以使用基于初始化的Swift Dependency Injection使它更好一点
So this subtle change makes a huge difference, instead of hardcoding file manager and network manager in the init method of FileUploader we are passing the required/dependency as parameters externally. This is basically what dependency injection is. We will talk about other flavors of dependency injection in coming articles.
因此,这种微妙的变化带来了很大的不同,我们没有在FileUploader的init方法中对文件管理器和网络管理器进行硬编码,而是在外部传递了所需的/依赖项作为参数。 这基本上就是依赖注入。 在接下来的文章中,我们将讨论依赖注入的其他形式。
Originally published at https://www.shashankthakur.dev.
最初发布在 https://www.shashankthakur.dev 。
翻译自: https://medium.com/swlh/how-to-do-swift-dependency-injection-with-initializers-1205ff830faf