WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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?

   

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

   

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

   

Gotcha. Beyond my knowledge set.

   

Thanks anyway man 🚀

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

   

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.