gpt4 book ai didi

ios - 是否可以将 AnyClass 传递给泛型函数

转载 作者:行者123 更新时间:2023-12-01 16:05:04 36 4
gpt4 key购买 nike

我试图将 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/

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