Using metatype in closure

99 Views Asked by At

Is it possible to use metatype in closures? The simplest example I came up with does not work

let type = String.self
let closure = { () -> type in
    return type.init()
}

Compiler complains at the second line about the type:

Use of undeclared type 'type'

I wonder is there a way to make it work?

If you are wondering the real use case is in dependency injection where I could inject related types in a forEach loop.

2

There are 2 best solutions below

0
Simon Moshenko On BEST ANSWER

I think I found a solution, I removed the return type to make it implicit and it worked. Probably it is some kind of swift compiler bug. End result:

let type = String.self
let closure = { () in
    return type.init()
}
1
Robert Dresler On

Rather then having type as constant, you can simply use generic constraint and then you just have to figure out how compiler can infer your type.

func makeSomething<T: YourProtocol>(...) {
    let closure = { () -> T in
        return T()
    }
}