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

Dependency Injection

Forums > Swift

Hi guys

What's the difference between this two?

class MyClass: {
  var someClass: SomeClass

  init(someClass: SomeClass = SomeClass()) {
     self.someClass = someClass
  }

}

And this other one

class MyClass: {
  var someClass: SomeClass

  init(someClass: SomeClass) {
     self.someClass = someClass
  }

}

I know theres an anti-patter called Bastard Injection where you pass a foreign default to the contructor, but in the case you're using the same class as default, it's ok? Theres something wrong in doing that?

2      

The first one creates a default instance of SomeClass. Below is a more basic example:

class MyClass {
  var someInt: Int

  init(someInt: Int = 5) {
     self.someInt = someInt
  }
}

let x = MyClass()
print(x.someInt)
// prints - 5

class MyClass2 {
  var someInt: Int

  init(someInt: Int) {
     self.someInt = someInt
  }
}

let y = MyClass2(someInt: 3)
// you are now required to supply a value
print(y.someInt)
// prints - 3

2      

Hi vtabmov, thanks for your reply.

I think I don't make myself clear with my question, its more about Dependecy Injection.

I got the part about the default value in the initializer, but what about code decoupling?

Using a default value with a foreign class is something like Bastard Injection or Poor Man Injection, but if I conform with the same exact class?

It's a anti-pattern too? Or it's ok

2      

Gotcha. Beyond my knowledge set.

2      

Thanks anyway man 🚀

Let's see if one of the monsters in the forum can elucidate it for me hehe

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.