gpt4 book ai didi

Swift:如何检查反射中的泛型类型?

转载 作者:行者123 更新时间:2023-11-28 06:25:04 25 4
gpt4 key购买 nike

我有以下模型:

class BaseClass { ... }
class WeakCollection<T: BaseClass> { ... }
class Person : BaseClass { ... }

class Parent : Person {
var children: [Child]
...
}

class Child : Person {
var parents: WeakCollection<Parent>
...
}

let aChild = Child()
...

我正在使用这样的反射:

let mirrored_object = Mirror(reflecting: aChild)
for attr in mirrored_object.children {
switch attr.value {
case is Int:
...

case is String:
...

case is WeakCollection<BaseClass>:
...
}
}

问题是检查case is WeakCollection<BaseClass>如果泛型类型不直接是 BaseClass,则始终为 false本身,也就是说,如果它是它的某些子类,则此检查将是错误的。如何检查通用类型?

最佳答案

一个粗略的方法是让你的“WeakCollection”继承自某种协议(protocol):

protocol BaseProtocol {}
class WeakCollection<T> : BaseProtocol

然后在你的开关中这样做:

switch attr.value {
case is String:
// This is a string
break
case let optionalObject as Optional<Any>:
if case .some(let complexObject) = optionalObject
{
if (complexObject is BaseProtocol)
{
// This is a "WeakCollection" kind
}
}
break
}

这有点粗糙,但它给出了你想要的输出。

关于Swift:如何检查反射中的泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42177861/

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