快速反射 - 如何检查反射值是否是一种类型

时间:2015-06-10 10:07:19

标签: ios swift reflection casting dynamictype

我有类似的设置:

protocol CoolProtocol {
}

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

当我尝试使用以下代码反映结构时,子数组无法正确识别为“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 个答案:

答案 0 :(得分:0)

也许这有用吗?:

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

}