Introduction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

What is Dependency Injection and why should you use it? Here’s an explanation from Swinject Tutorial for iOS: Getting Started:

Dependency Injection is an approach to organizing code so that its dependencies are provided by a different object, instead of by itself. Arranging code like this leads to a codebase of loosely-coupled components that can be tested and refactored. Dependency Injection relies on a principle called Inversion of Control. The main idea is that a piece of code that requires some dependencies won’t create them for itself, rather the control over providing these dependencies is deferred to some higher abstraction. These dependencies are typically passed into an object’s initializer. This is the opposite approach — an inverted approach — to the typical cascade of object creation: Object A creating Object B, creating Object C, and so on. From a practical perspective, the main benefit of Inversion of Control is that code changes remain isolated.

MVVM (Model View ViewModel) architecture implements dependency injection (DI) by separating data management (view model) from data presentation (view). This means every view depends on its view model to provide it with everything it needs instead of creating these internally. MVVM designs are more flexible, helping you create loosely coupled apps.

A common problem with dependency injection is how to provide a view with a dependency it needs without passing it through all of its ancestors in the view hierarchy. In Lesson 3, you learned how to do this with @Environment.

You can also use dependency injection to improve the performance or convenience of previews. You’ll learn how in this lesson.

Encapsulating presentation logic in view models also helps when writing unit tests. You’ll work with a simple example in this lesson.

Learning Objectives

In this lesson, you’ll learn to:

See forum comments
Download course materials from Github
Previous: Data Binding Techniques Quiz Next: Dependency Injection in MVVM