DEV Community

NalineeR
NalineeR

Posted on • Edited on

Dependency Injection in swift

The approach used to provide the initial value to the property.
The purpose of this approach is to obtain the loosely coupled code.

There are three type to obtain this -

By Initialisation -> In this type we need to pass the initialisation value in the init func of the class

class DemoVC:UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        //passing dependency value by init func
        let obj = Language(langName: "Swift")
        print(obj.name)
    }
}

class Language{
    var name:String
    ///1. Initialisation Dependency Injection
    init(langName:String) {
        self.name = langName
    }
}
Enter fullscreen mode Exit fullscreen mode

By Function -> In this type we pass the initial value as the function param. And the class property is initialised from this param.

class DemoVC:UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        //setting dependency value passing parameter in method
        let obj = Language()
        obj.getLanuageDetails(lanugage: "Swift")
    }
}

class Language{
    private var name:String!
    func getLanuageDetails(lanugage:String){
        name = lanugage
        print("Your have shown interest in \(lanugage) Language.")
    }
}
Enter fullscreen mode Exit fullscreen mode

By Property -> Here we generally create / access the class property and set the value directly.

class DemoVC:UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        //setting dependency value by setting property directly
        let obj = Language()
        obj.name = "Objective C"
    }
}

class Language{
    var name:String = "Swift"
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sergeyleschev profile image
Sergey Leschev

In my experience working with Swift and iOS development, I have found that using dependency injection is crucial when building large-scale applications. It helps avoid code duplication, enhances testability and modularity. Moreover, it makes the code reusable, readable, and easy to maintain.