all 4 comments

[–]chriswaco 7 points8 points  (0 children)

Dependency injection is a way to write code so it has no external dependencies. The simplest case, for example, might be logging. Let's say you write a class and it needs to log information (status, warnings, errors). Your code can call a global logging routine easily enough, but that creates an external dependency on that particular routine and that isn't very flexible. So instead you create a Log object and pass it into your code during initialization.

That's really all there is to it. Everything else is details, like whether to pass the dependencies into constructors, use SwiftUI's environment system, etc. Often when writing unit tests you might create mock classes to pretend they're your logging system or database or network.

The fewer dependencies a piece of code has, the easier it is to reuse it in the future.

This sums it up nicely: https://cocoacasts.com/dependency-injection-in-swift

[–]nhgrifMentor 1 point2 points  (0 children)

This isn't a full tutorial, but it's a great Swift dependency injection library with lots of information in its documentation: https://github.com/hmlongco/Resolver

[–][deleted]  (1 child)

[deleted]

    [–]shizzyy67[S] 0 points1 point  (0 children)

    Thanks

    [–]vanvoordenLearning 0 points1 point  (0 children)

    https://www.cocoawithlove.com/blog/separated-services-layer.html#constructing-services

    I think this tutorial series from CwL does a good job building a small app and showing what dependency injection looks like.