Discover how handing over your tools can make your code smarter and easier to manage!
Why Dependency injection in iOS Swift? - Purpose & Use Cases
Imagine building an app where every part creates its own tools and helpers inside. For example, a screen creates its own network manager and database handler directly.
This manual way makes your code tightly connected and hard to change. If you want to swap the network manager or test the screen, you must dig deep and rewrite many parts. It's like having a tangled ball of yarn that's tough to separate.
Dependency injection hands the needed tools to each part from outside. Instead of creating them inside, parts receive what they need. This keeps code clean, easy to swap, and simple to test.
class Screen {
let network = NetworkManager()
// uses network directly
}class Screen {
let network: NetworkManager
init(network: NetworkManager) {
self.network = network
}
// uses injected network
}It enables flexible, testable, and maintainable code by separating creation from usage.
Think of a coffee shop where the barista gets coffee beans delivered instead of growing them. The barista focuses on making coffee, while the beans can come from any supplier.
Manual creation leads to tightly coupled code.
Dependency injection separates creation from use.
This makes code easier to change and test.
Practice
Solution
Step 1: Understand dependency injection concept
Dependency injection means giving an object the things it needs (dependencies) from outside instead of creating them inside the object.Step 2: Identify the main purpose
This approach helps keep code flexible, easier to test, and cleaner by separating concerns.Final Answer:
To provide objects with their dependencies from outside rather than creating them inside -> Option AQuick Check:
Dependency injection = provide dependencies from outside [OK]
- Thinking it speeds up app performance
- Confusing with UI generation
- Mixing with data encryption
Solution
Step 1: Identify constructor injection pattern
Constructor injection means passing dependencies through the initializer (init) of a class.Step 2: Check which code passes dependency via init
class Service { init() { } } class Client { let service: Service; init(service: Service) { self.service = service } } shows a Client class receiving a Service instance through its init method and storing it.Final Answer:
class Service { init() { } } class Client { let service: Service; init(service: Service) { self.service = service } } -> Option BQuick Check:
Constructor injection uses init to pass dependencies [OK]
- Creating dependencies inside the class instead of passing them
- Using methods instead of init for injection
- Not storing the injected dependency
protocol Logger { func log(_ message: String) }
class ConsoleLogger: Logger { func log(_ message: String) { print("Console: \(message)") } }
class Client {
let logger: Logger
init(logger: Logger) { self.logger = logger }
func doWork() { logger.log("Work done") }
}
let client = Client(logger: ConsoleLogger())
client.doWork()Solution
Step 1: Understand the Logger protocol and ConsoleLogger class
ConsoleLogger implements Logger and prints messages prefixed with "Console:".Step 2: Trace the Client usage
Client is initialized with ConsoleLogger and calls logger.log("Work done"), which prints "Console: Work done".Final Answer:
Console: Work done -> Option CQuick Check:
Injected ConsoleLogger prints with "Console:" prefix [OK]
- Ignoring the prefix in print statement
- Assuming no output because of protocol
- Confusing method names
protocol DataService { func fetchData() -> String }
class RealDataService: DataService { func fetchData() -> String { "Real Data" } }
class ViewModel {
var dataService: DataService
init() { }
func load() -> String { dataService.fetchData() }
}Solution
Step 1: Check property initialization
ViewModel has a non-optional property dataService but its init() does not initialize it.Step 2: Understand Swift initialization rules
Non-optional properties must be initialized before use; missing initialization causes a compile error.Final Answer:
dataService is not initialized before use -> Option AQuick Check:
Non-optional properties must be initialized [OK]
- Assuming default nil for non-optional
- Confusing return types
- Ignoring protocol conformance
NetworkManager testable by injecting a protocol NetworkService. Which approach best applies dependency injection and allows easy swapping of real and mock services?Solution
Step 1: Understand testability with dependency injection
To test NetworkManager easily, inject a protocol so you can swap real and mock implementations.Step 2: Identify best practice
Passing NetworkService via init allows NetworkManager to use any implementation, making testing flexible.Final Answer:
Define a NetworkService protocol, make NetworkManager accept it via init, and pass either real or mock implementations when creating NetworkManager -> Option DQuick Check:
Inject protocol via init for flexible testing [OK]
- Hardcoding real service inside class
- Using global variables causing tight coupling
- Misusing inheritance instead of composition
Ready to prove it?
Pass the test and this pattern moves unknown
