NathanVss
NathanVss

Reputation: 644

Swift - Closure pattern

I'm reading docs about Swinject and I don't understand two things in this code :

let container = Container()
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
container.register(PersonType.self) { r in
    PetOwner(pet: r.resolve(AnimalType.self)!)
}

How the to two closures are standing alone and are not embeded in method call ? The closures are not returning any object, I don't see any 'return'. So how the container can get the "Cat" instance ? ( And also the PetOwner instance ).

Thank you

Upvotes: 2

Views: 296

Answers (1)

0x416e746f6e
0x416e746f6e

Reputation: 10136

  1. "two closures are standing alone and are not embeded in method call"

This is so called "trailing closure":

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is a closure expression that is written outside of (and after) the parentheses of the function call it supports...

Source: Apple's documentation

  1. "The closures are not returning any object, I don't see any 'return'"

The feature is called "implicit return":

Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration...

Source: Apple's documentation

Upvotes: 4

Related Questions