从字符串创建 classType 以作为具体类型传递给泛型参数 Swift

Creating classType from string to pass as concrete type to generic parameter Swift

我有 protocol Pclass A and B,我的目标是使用从字符串创建的 class 类型参数调用泛型方法 a<T: P>(_: T.Type)

protocol P: class {
    static var p: String { get }
}

extension P {
    static var p: String { return String(describing: self) }
}

class A: P {

    func a<T: P>(_: T.Type) {
        print(T.p)
    }
}

class B: P {}

以下代码有效,因为强制转换为 B.Type 修复了 class 类型

let b = "B"
let type = NSClassFromString(b) as! B.Type
A().a(type)

但是如果假设我们有一个包含 class 个名称的数组但不知道它们的具体类型,我们如何传递这些名称?

["ClassA", "ClassB", "ClassC"].forEach({ className in
   let type = NSClassFromString(className) as! ????
   A().a(type)
})

在Swift中,泛型声明中的类型参数需要在编译时解决。

因此,您的 ???? 需要是符合 P 的具体类型。但是您不能像您描述的那样使用任何具体类型 A.TypeB.Type

而且您可能知道您不能使用 P.Type,因为协议 P 不符合 Swift.

中的 P 本身

如何将方法 a(_:) 声明为非泛型?

class A: P {

    func a(_ type: P.Type) {
        print(type.p)
    }

}

["ModuleName.A", "ModuleName.B"].forEach({ className in
    let type = NSClassFromString(className) as! P.Type
        A().a(type)
})

您可以将 class 个 P.Type 类型的对象传递给 P.Type 类型的参数。