Skip to content

Resolving optionals

Ilya Puchka edited this page Aug 26, 2016 · 2 revisions

Dip can inject dependencies defined as optionals (both with ? and !) either in constructor or in a property. That can be handy if you don't want to rely on Swift type inference instead of explicitly specifying the type that you want to resolve.

Let's say you have some service with optional constructor or property dependency:

class Service {
   var logger: Logger!
   init(client: Client?) { ... }
}

container.register { Client() }
container.register { Logger() }

You could register Service explicitly providing types of its dependencies:

container.register { try Service(client: container.resolve() as Client) }
  .resolvingProperties { container, service in
    service.logger = try container.resolve() as Logger
}

But as Dip can resolve optionals we can omit those types:

container.register { try Service(client: container.resolve()) }
  .resolvingProperties { container, service in
    service.logger = try container.resolve()
}

Compiler will infer types to resolve as Client? and Logger! and Dip will resolve them using definitions that you registered for Client and Logger type.