Complete the code to declare a protocol for dependency injection.
protocol [1] {
func fetchData() -> String
}The protocol defines the contract for the service. Naming it ServiceProtocol clearly indicates its role.
Complete the code to inject a dependency via initializer.
class ViewModel { let service: ServiceProtocol init([1]: ServiceProtocol) { self.service = service } }
The parameter name service matches the property and type, making the code clear and consistent.
Fix the error in the code by completing the injection of a mock service.
class MockService: [1] { func fetchData() -> String { return "Mock Data" } }
The mock class must conform to the ServiceProtocol to be used as a dependency.
Fill both blanks to create a property and assign it in the initializer for dependency injection.
class Controller { private let [1]: ServiceProtocol init([2]: ServiceProtocol) { self.service = service } }
The property and initializer parameter should both be named service to keep the code clear and consistent.
Fill all three blanks to complete a function that uses dependency injection to fetch data.
func displayData(using [1]: [2]) -> String { return [3].fetchData() }
The function parameter name is service of type ServiceProtocol, and the method calls service.fetchData().