Dependency injection in swift
Dependency injection in swift is a design pattern and in this swift tutorial for beginners, we shall explore what is dependency injection in swift.
We are going to explore topics such as
1. Constructor injection
2. Property injection
These two are the types of dependency injection that are used most of the time in swift programming language and if you use them during ios development your codebase will have no hidden dependency.
This swift tutorial has easy to understand dependency injection swift example for beginners and experienced programmers who want to learn the dependency injection concept.
import UIKit
struct Endpoints {
static let getList = "http://demo2502014.mockable.io/getListData"
}
class HttpClient {
func getData(url:URL, completionHandler:@escaping (_ data: Data?) -> Void) {
URLSession.shared.dataTask(with: url) { dataResponse, result, error in
completionHandler (dataResponse)
}.resume ()
}
}
class ListData {
var client : HttpClient? = nil
/* for Constructor injection we have to declare init method */
init(_client: HttpClient) {
client = _client
}
func getListRecord()
{
let client : HttpClient = HttpClient() // hidden Dependency of HttpClient (we have to resolve it with help of property injection & Constructor injection)
client.getData(url: URL(string: Endpoints.getList)!) { data in
if data?.count != 0 {
debugPrint ("response data = \(String (describing: data? .count))")
}
}
}
}
let ObjData = ListData (_client: HttpClient ()) // Constructor injection
ObjData.client = HttpClient () // Property injection
ObjData.getListRecord()