[英]Swift: How to check for generic type in a reflection?
I have following model:我有以下型号:
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()
...
I'm using a reflection like this:我正在使用这样的反射:
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>:
...
}
}
The problem is the check in the case is WeakCollection<BaseClass>
is always false if the generic type is not directly the BaseClass
itself, that is if it is some of its subclasses this check will be false.问题是在
case is WeakCollection<BaseClass>
的检查总是假如果泛型类型不是直接BaseClass
本身,也就是说,如果它是它的一些子类,则此检查将是假的。 How can I check for the generic type?如何检查泛型类型?
A rough way of doing that, is to make your "WeakCollection" inherit from some kind of protocol:一个粗略的方法是让你的“WeakCollection”从某种协议继承:
protocol BaseProtocol {}
class WeakCollection<T> : BaseProtocol
And then in your switch do it like this:然后在您的交换机中这样做:
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
}
This is a bit rough, but it gives out the output you want.这有点粗糙,但它给出了你想要的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.