iosswiftxcodemetaprogrammingmetatype

Using metatype in closure


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.


Solution

  • 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()
    }