gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:20 26 4
gpt4 key购买 nike

我有 protocol P , class A and B我的目标是调用通用方法 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 修复了类类型

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

但是如果假设我们有一个类名数组而不知道它们的具体类型,我们如何传递它们呢?

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

最佳答案

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

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

你可能知道你不能使用 P.Type,因为协议(protocol) 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 - 从字符串创建 classType 以作为具体类型传递给泛型参数 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50910169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com