简体   繁体   中英

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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM