[英]Swift reflection - How to check if a reflected value is a kind of type
我有一個與此類似的設置:
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
}
}
也許行得通嗎?:
let valueType = "\(mi.valueType)"
if valueType == "\(reflect([Node]()).valueType)" {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.