在闭包中使用元类型

Using metatype in closure

是否可以在闭包中使用元类型?我想出的最简单的例子不起作用

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

编译器在第二行抱怨 type:

Use of undeclared type 'type'

我想知道有没有办法让它起作用?

如果您想知道真正的用例是依赖注入,我可以在 forEach 循环中注入相关类型。

与其将类型作为常量,您可以简单地使用泛型约束,然后您只需要弄清楚编译器如何推断您的类型。

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

我想我找到了一个解决方案,我删除了 return 类型以使其隐式并且有效。可能是某种 swift 编译器错误。最终结果:

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