我试图将AnyClass传递给这样的通用函数:
if let arrayObjectClass = NSClassFromString("arrayObjectTypeName") {
foo(type: arrayObjectClass)
}
foo
如下所示:func foo<T>(type: T.Type) {
...
}
但无法编译并显示错误:Cannot convert value of type 'AnyClass' (aka 'AnyObject.Type') to expected argument type 'T.Type'
最佳答案
编译器在那里需要您的T
的类型。您的AnyClass
实例不是类型。因此,您的foo
将需要知道该类应该是什么。这必须在运行时完成。
if let arrayObjectClass = NSClassFromString("arrayObjectTypeName") {
try foo(class: arrayObjectClass, arrayObjectTypeName.self)
}
func foo<T>(class: AnyClass, _: T.Type) throws {
if let error = CastError(`class`, desired: T.self)
{ throw error }
}
/// An error that represents casting gone wrong. 🧙♀️🙀
public enum CastError: Error {
/// An undesired cast is possible.
case possible
/// An desired cast is not possible.
case impossible
}
public extension CastError {
/// `nil` if an `Instance` can be cast to `Desired`. Otherwise, `.impossible`.
init?<Instance, Desired>(_: Instance, desired _: Desired.Type) {
self.init(Instance.self, desired: Desired.self)
}
/// `nil` if a `Source` can be cast to `Desired`. Otherwise, `.impossible`.
init?<Source, Desired>(_: Source.Type, desired _: Desired.Type) {
if Source.self is Desired.Type
{ return nil }
self = .impossible
}
/// `nil` if an `Instance` cannot be cast to `Undesired`. Otherwise, `.possible`.
init?<Instance, Undesired>(_: Instance, undesired _: Undesired.Type) {
self.init(Instance.self, undesired: Undesired.self)
}
/// `nil` if a `Source` cannot be cast to `Undesired`. Otherwise, `.possible`.
init?<Source, Undesired>(_: Source.Type, undesired _: Undesired.Type) {
guard Source.self is Undesired.Type
else { return nil }
self = .possible
}
}
关于ios - 是否可以将AnyClass传递给泛型函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63965020/