通过索引获取Mirror.Child的Child

时间:2016-01-31 20:46:31

标签: swift

我知道我可以使用foreach来快速遍历反射对象的子项......

struct demo{

    let b = 2
    let a = 1
    let c = 3




}

let obj = demo()
let reflected = Mirror( reflecting: obj)
let obj = demo()
let reflected = Mirror( reflecting: obj)
for child in reflected.children{
print(child.label)
}

是否可以通过索引访问子项。像

// refelected.children[index]  this is not a valid syntax

如何在不使用for循环的情况下通过索引访问每个子节点。感谢。

3 个答案:

答案 0 :(得分:2)

Children类型实际上是AnyForwardCollection<Child>的typedef。

您无法使用任何旧AnyForwardCollection索引Int。您需要使用AnyForwardIndex。您可以使用startIndex获取起始索引,advancedBy()继续前进。

let obj = demo()
let reflected = Mirror( reflecting: obj)

let idx = reflected.children.startIndex
let first = reflected.children[idx]
let thirdIdx = idx.advancedBy(2)
let third = reflected.children[thirdIdx]

答案 1 :(得分:0)

此外,根据Kevins的回答,我会稍微更新Swift 3。

let obj = demo()
let reflected = Mirror(reflecting: obj)
let index: IntMax = 3
let reflectedChildAtIndex = reflected.children.index(reflected.children.startIndex, offsetBy: i, limitedBy: reflected.children.endIndex)

答案 2 :(得分:0)

我想要哈里·布鲁姆(Harry Bloom)的答案,因为这是最优雅的方式,但是有一个错字:“ i”必须为“索引” ,并且我添加了以下行:指定索引处的项目。

let obj = demo()
let mirror = Mirror(reflecting: obj)
let index = 3 // careful: max. not checked, just an example
let idx = mirror.children.index(mirror.children.startIndex, offsetBy: index, limitedBy: mirror.children.endIndex)
let valueOfChildAtIndex =  mirror.children[idx!]