Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从字符串创建类类型,作为具体类型传递给泛型参数Swift_Swift_Generics_Swift Protocols - Fatal编程技术网

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

从字符串创建类类型,作为具体类型传递给泛型参数Swift,swift,generics,swift-protocols,Swift,Generics,Swift Protocols,我有protocolp,class A和B,我的目标是使用从字符串创建的class-Type参数调用泛型方法A(: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) {

我有
protocolp
class A和B
,我的目标是使用从字符串创建的class-Type参数调用泛型方法
A(: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 {}
但是如果假设我们有一个类名数组,而不知道它们的具体类型,那么我们如何传递它们呢

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

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

因此,您的
需要是符合
p
的具体类型。但是您不能使用您描述的任何具体类型
A.Type
B.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)
})

您可以将类型为
p.type
的类对象传递给类型为
p.type

的参数。您是否研究了Swift
KeyPath
?请参阅:@user1046037要定义密钥路径,我们不需要根类型吗?同样的事情我们需要知道。
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)
})