UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Understanding Dependency Injection - Swift

Forums > Swift

Hi, I would like to have a better understanding of Dependency Injection, in general, to start using it.

Based on the three examples below, can someone please point out what would be the pros and the cons of using one over the other?

1 - What problem could Example 1 cause if I don't do unitest? This is my current method.

2- What method of Dependency Injection is best to adopt, Example 2 ro Example 3?

3- I noticed that Example 2 enforces to provided the dependency object at instantiation time whereas Example 3 does not. Couldn't Example 3 create confusion for the programmer since if you don't provide the dependency object, the code will still compile without any warning if you call a function that relies on a method inside the injected object?

Example 1: Without Dependency Injection

class Stereo{
   func volume(){
     print("Adjusting volume...")
   }
}

class Car{
  var stereo = Stereo()

  func adjustVolume(){
    stereo.volume()
  }
}

let car = Car()
car.adjustVolume()

Example 2: With Dependency Injection

class Stereo{
   func volume(){
     print("Adjusting volume...")
   }
}

class Car{
  var stereo: Stereo

  init(stereo: Stereo){
    self.stereo = stereo
  }

  func adjustVolume(){
    stereo.volume()
  }
}
let car = Car(stereo: Stereo())
car.adjustVolume()

Example 3: With Optional Dependency Injection

class Stereo{
   func volume(){
     print("Adjusting volume...")
   }
}

class Car{
  var stereo: Stereo?

  func adjustVolume(){
    stereo?.volume()
  }
  // this method can be called without injecting Stereo 
  func someOtherFunction(){
    print("Calling some other function...")
  }
}

let car = Car()
car.stereo = Stereo()
car.adjustVolume()

Thanks

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.