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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.