【问题标题】:Swift reflection - How to check if a reflected value is a kind of type快速反射 - 如何检查反射值是否是一种类型
【发布时间】:2015-08-25 12:33:54
【问题描述】:

我有一个类似的设置:

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
        }

}

【问题讨论】:

    标签: ios swift reflection casting dynamictype


    【解决方案1】:

    也许这行得通?:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2021-08-11
      • 2013-02-02
      • 2019-10-18
      • 1970-01-01
      • 2010-09-17
      • 2013-06-15
      相关资源
      最近更新 更多