Dependency injection is a powerful design pattern that allows multiple components in your application to be decoupled from each other, making your code more modular and easier to test. Here's a simple example of how you can implement dependency injection in Swift:
main.swift974 chars37 lines
In this example, we define a protocol DataService
that defines a method fetchData()
which returns an array of strings. We then implement the protocol in the LocalDataService
class to fetch the data from a local source.
We then use dependency injection by creating an instance of ViewController
and passing it an instance of LocalDataService
as a parameter to its initializer. The ViewController
class can then use the dataService
property to retrieve the data.
Using dependency injection in this way makes it easy to test the ViewController
class by creating a mock implementation of DataService
that can be passed as a parameter to its initializer during testing.
gistlibby LogSnag