DEV Community

NalineeR
NalineeR

Posted on • Edited on

2 1 1 1 1

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay