Injecting dependencies cleanly in UIKit with Swift can greatly enhance the maintainability and testability of your application. Below are some techniques you can use for dependency injection, including property injection, initializer injection, and method injection.
With property injection, dependencies are set after the object is created, which can help in testing scenarios where you might want to change the dependency at runtime.
class ViewController: UIViewController {
var myService: MyServiceProtocol?
override func viewDidLoad() {
super.viewDidLoad()
myService?.performAction()
}
}
Initializer injection allows you to pass dependencies through the initializer, making your object more predictable and reducing side effects.
class ViewController: UIViewController {
private let myService: MyServiceProtocol
init(myService: MyServiceProtocol) {
self.myService = myService
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
myService.performAction()
}
}
Method injection involves passing dependencies through a method call, which can be useful for temporary or optional dependencies.
class ViewController: UIViewController {
func configure(with service: MyServiceProtocol) {
service.performAction()
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?