Swift reflection - How to check if a reflected value is a kind of type

371 views Asked by At

I have a setup similar to this:

protocol CoolProtocol {
}

Node : CoolProtocol {
  children : [Node]
... other properties
}

When I try to reflect the structure with the following code , the children array isn't recognized correctly as a "list of CoolProtocol"

reflectIt(something : Any) -> [String : AnyObject] {
    var t = reflect(anything)
    var dict = [String : AnyObject]()
    for i in 0..<t.count {
        var (key,mirror) = t[i]
// High priority for this protocol so it is the first check
        if mirror.value is CoolProtocol {
            var val = mirror.value
            println(val)
            dict[key] = reflectIt(mirror.value)
            continue
        }
        // next priority for arrays of Nodes
        // i've tried doing if let value = mirror.value as? [Node] but it never works - 
//here is another variation that never works
        if mirror.value is [Node] {
            let valuearray = mirror.value as! [Node]
            var arr = [[String : AnyObject]]()
            for (index,child) in enumerate(valuearray) {
                arr.append(serialize(child))
            }
            dict[key] = arr
            continue
        } else if let value = mirror.value as? DebugPrintable {
// next priority for debug descriptions
            dict[key] = value.debugDescription
        } else if let value = mirror.value as? Printable {
// final priority for regular descriptions
            dict[key] = value.description
        }

}
1

There are 1 answers

0
Edwin Vermeer On

Maybe this works?:

let valueType = "\(mi.valueType)"
if valueType == "\(reflect([Node]()).valueType)" {

}