How to implement Dependency Injection in Swift!
HTML-код
- Опубликовано: 24 янв 2022
- 🔥 Big thank you to Stream for sponsoring this video! 🔥
Stream's enterprise-grade chat makes it easy for developers to quickly add real-time messaging to their applications, check out their website 👉 gstrm.io/Vincent
---
#iOS #swift #softwaredeveloper #iosdeveloper
Thank you for watching this video 🙌
Get the code 👉 bit.ly/35hDHRN
I use Ecamm Live to record my videos, check it out 👉 bit.ly/3n9CClf
(affiliate link)
➜ Leave a tip: www.buymeacoffee.com/v.pradei...
➜ Website: www.swiftwithvincent.com
➜ Twitter: / v_pradeilles
➜ GitHub: github.com/vincent-pradeilles/
➜ LinkedIn: / vincentpradeilles Наука
Did you enjoy this introduction to Dependency Injection in Swift? Let me know in the comments 🚀
As always a great video, super objective and clear. Thank you Vincent!
Thanks! Could be useful a new video explains how to manage dependency injections classes with a big project
Great explanation, thanks Vincent!
Thanks Vincent, great explanation.
Awesome video and love your channel. Just wanted to suggest another specific approach when injecting dependencies to storyboard view controllers.
Storyboard ViewControllers with dependency injection have a problem of breaking encapsulation due to the fact you have to keep your dependencies public thus risking it being overwritten from the outside at a later time.
This approach prevents that (though I honestly just prefer to use programmatic view controller to avoid the whole thing completely):
class ViewController: UIViewController {
//Can remain private since we are using inner static init.
private var someDependency: SomeDependency!
//Static init
static func instantiate(someDependency: SomeDependency) -> Self {
let vc = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "Identifier") as! Self
vc.someDependency = someDependency
return vc
}
override func viewDidLoad() {
super.viewDidLoad()
//Use dependency here
}
}
thank you, the best
nice explanation.
Hi, nice video. I often get asked the interview question. "Imagine if you have really large array what will be most appropriate way to handle it will you use value type or reference type?" I will really appreciate if you make a video addressing this. Merci bonne journée
hi this is an interesting problem. have you figured out the explanation? im also preparing for my interview 🙏
Thanks Vincent for the video it does solve the problem of taking away the responsibility of the scene delegate to create the first ViewController. However I have a few questions with the Dependency provider structure which you have presented and would really like to get your view on my questions below.
1. Is there a better way to create Dependency provider ? .
2. Currently your DependencyProvider is a struct and it creates ViewModel and ViewController within it which I assume are a class. So in theory your struct is having class instances.
3. Is it really required for the struct to have static variables ? Can DependencyProvider just be a class with all the variables in it ?
i think he was using struct because as the term "provider" that was only called and needed once. i see it as a one-time use, and the struct will then be destroyed in memory (since struct is a value type)
Thanks, Vincent for this introduction, just wondering shouldn't the class TesService conform to the protocol Servicing and not inherit from class Service
Good question! Here the interest of subclassing Service is that we can call super, getting along the way a working implementation for free.
But in a real project that calls live web services, it would indeed make sense to create a test instance that would directly implement Servicing and provide its own mocked implementation.
Hey, thanks for this video !
I wonder what's the implem when it comes to having a lot of VCs ? do you create multiples DependencyProvider ? what about navigation ?
For a big project, I would recommend looking at a framework like Swinject that's going to help you split and manage the code that resolves dependencies 👉 github.com/Swinject/Swinject
Thoroughly explained, don't the objects in the dependency manager stay longer than needed?
Good question!
In my example all the properties of my DependencyProvider are computed properties, so they don't store anything and produce a new value each time they're called.
However, this is a simplified implementation. Dependency Injection frameworks, like Swinject, will indeed typically implement a mechanism to manage the lifetime of stored dependencies 👍
@@v_pradeilles thank you for clearing it out ☺️
XCTestExpectation seems more appropriate to use for checking that the viewModel calls the service only once
class MockedService: Servicing {
let expectation = XCTestExpectation(description: "callCount")
func getData(_ completion: @escaping (Int) -> Void) {
expectation.fulfill()
}
}
class ViewModelTests: XCTestCase {
func testViewModelCallsService() {
let service = MockedService()
let vm = ViewModel(service: service)
vm.fetchData()
wait(for: [service.expectation], timeout: 1)
}
}
actually, I don't think this does test the actual method which could still be being called twice. i doubt we would want to call the method `getData(_:)` directly in a unit test anyway assuming it's concurrent and hits an external dependency.
Yeah I agree that in a real test, our mock wouldn't call the real implementation and instead would provide static data.
I don't understand why I should use dependency injection in my app.
Why not just pass the vm. why not just just instantiate the service ?
It makes 0 sense to me.
As swiftUI has not the issue of init. Is it even useful ?
hi. are you in the apple developer academy?
Why is the DependencyProvider a struct and not a class?
That’s a good remark! As you can see, DependencyProvider only has static members, and so we never need to instantiate it. So we could make it easier a class, a struct or an enum: it wouldn’t change anything.
How can this be done in SwiftUI ? or is dependency injection not needed in SwiftUI ?
Great question! SwiftUI actually had a built in implementation of Dependency Injection, which is called the “Environment” 👌
@@v_pradeilles thats nice.
Thanks Vincent, great explanation.