1

Am I susceptible to memory leaks if I inject dependencies as classes and not as instances? The reason I want to do this is that the 3rd-party library I am integrating only exposes class methods. Is it dangerous if I do just that? (and why and when would this danger show up):

var service: ServiceProtocol.Type

init(withService service: ServiceProtocol.Type = Service.self) {
        self.service = service
    }

and then inside the class I just call a method like this:

self.service.doSomething()

1 Answers1

1

It is safe. Service.self is just a reference to the type, and types exists during the whole runtime of the program anyway, so it doesn't introduce any additional expenses.

One thing you should be careful with in this case is allocating "static" memory. For example if self.service.doSomething() adds an element to an array that is a static field of the class, make sure to clean it up when it is no longer needed. Otherwise it will stay in memory until the program is terminated.

Vyacheslav Pukhanov
  • 1,788
  • 1
  • 18
  • 29