0
0
iOS Swiftmobile~10 mins

Dependency injection in iOS Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a protocol for dependency injection.

iOS Swift
protocol [1] {
  func fetchData() -> String
}
Drag options to blanks, or click blank then click option'
ADataService
BInjectable
CDependency
DServiceProtocol
Attempts:
3 left
💡 Hint
Common Mistakes
Using a class name instead of a protocol name
Using vague names like 'Dependency'
2fill in blank
medium

Complete the code to inject a dependency via initializer.

iOS Swift
class ViewModel {
  let service: ServiceProtocol

  init([1]: ServiceProtocol) {
    self.service = service
  }
}
Drag options to blanks, or click blank then click option'
AserviceProtocol
Bdependency
Cservice
DdataService
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name that confuses the assignment
Forgetting to assign the parameter to the property
3fill in blank
hard

Fix the error in the code by completing the injection of a mock service.

iOS Swift
class MockService: [1] {
  func fetchData() -> String {
    return "Mock Data"
  }
}
Drag options to blanks, or click blank then click option'
AService
BServiceProtocol
CInjectable
DDataService
Attempts:
3 left
💡 Hint
Common Mistakes
Conforming to a class instead of a protocol
Using incorrect protocol names
4fill in blank
hard

Fill both blanks to create a property and assign it in the initializer for dependency injection.

iOS Swift
class Controller {
  private let [1]: ServiceProtocol

  init([2]: ServiceProtocol) {
    self.service = service
  }
}
Drag options to blanks, or click blank then click option'
Aservice
Bdependency
DdataService
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for property and parameter
Using vague names like 'dependency'
5fill in blank
hard

Fill all three blanks to complete a function that uses dependency injection to fetch data.

iOS Swift
func displayData(using [1]: [2]) -> String {
  return [3].fetchData()
}
Drag options to blanks, or click blank then click option'
Aservice
BServiceProtocol
DdataService
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching parameter name and usage
Using incorrect protocol or variable names