Choose the best explanation for why developers use dependency injection in Swift apps.
Think about how dependency injection affects how objects get what they need to work.
Dependency injection means giving an object its dependencies from outside, which reduces tight coupling and makes testing easier.
Consider this Swift code using dependency injection. What is the output?
protocol Logger {
func log(_ message: String)
}
class ConsoleLogger: Logger {
func log(_ message: String) {
print("Console: \(message)")
}
}
class FileLogger: Logger {
func log(_ message: String) {
print("File: \(message)")
}
}
class Service {
let logger: Logger
init(logger: Logger) {
self.logger = logger
}
func doWork() {
logger.log("Work done")
}
}
let service = Service(logger: FileLogger())
service.doWork()Look at which logger instance is passed to the Service.
The Service is initialized with a FileLogger instance, so it prints "File: Work done".
Choose the correct Swift code snippet that injects a dependency via the initializer.
Initializer injection requires the dependency to be passed and assigned in the init method.
Option A declares the property and assigns it in the initializer, which is the correct pattern for initializer injection.
Examine the code below. What causes the crash when creating ViewController?
class Service {} class ViewController { var service: Service! init() { // service is not initialized here } func useService() { print(service!) } } let vc = ViewController() vc.useService()
Check how the service property is declared and when it is assigned.
The implicitly unwrapped optional service is nil when useService is called, causing a runtime crash.
counter after running this Swift code with dependency injection?Analyze the code below. What value does counter have after incrementer.increment() is called?
protocol Incrementable {
func increment()
}
class Counter: Incrementable {
var count = 0
func increment() {
count += 1
}
}
class Incrementer {
let counter: Counter
init(counter: Counter) {
self.counter = counter
}
func increment() {
counter.increment()
}
}
let counter = Counter()
let incrementer = Incrementer(counter: counter)
incrementer.increment()
let finalCount = counter.countTrace how the count property changes when increment() is called.
The increment() method increases count by 1, so the final value is 1.