我有以下型号:
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,即如果它是某些子类,则此检查将为false。如何检查通用类型?
答案 0 :(得分:1)
这样做的一个粗略方法是制作你的&#34; WeakCollection&#34;继承了某种协议:
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
}
这有点粗糙,但它会给出你想要的输出。