Dependency Injection Tutorial for iOS: Getting Started

Dependency Injection Tutorial for iOS: Getting Started

Programmers have developed many architectures, design patterns and styles of programming. While they each solve different problems, all of them help make code more readable, testable and flexible.

[…]

Before you can give them that control and learn more about Dependency Injection and how it can help you, you need to identify the issue.

[…]

However, you can improve the situation and seamlessly add new functionality with Dependency Injection.

[…]

Dependency Injection is one of a few patterns that helps apply principles of Inversion of Control. You can implement Dependency Injection in several ways, including Constructor Injection, Setter Injection and Interface Injection.

[…]

In Constructor Injection, or Initializer Injection, you pass all the class dependencies as constructor parameters. It’s easier to understand what the code does because you immediately see all the dependencies a class needs in one place. For example, look at this snippet:

[…]

Setter Injection, or Method Injection, is sightly different. As you can see in this example, it requires dependency setter methods:

[…]

Interface Injection requires the client conforms to protocols used to inject dependencies. Look at this example:

[…]

Next, update the provider which will handle a new privacy level. Go to ProfileContentProvider.swift and update the following properties:

[…]

With the code above, you let your UserPreferencesView receive the needed dependency, instead of creating it on its own.

[…]