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

Billboard image

Use Playwright to test. Use Playwright to monitor.

Join Vercel, CrowdStrike, and thousands of other teams that run end-to-end monitors on Checkly's programmable monitoring platform.

Get started now!

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️