swift 获取镜像的子项,按索引查找子项

ttisahbt  于 2023-05-16  发布在  Swift
关注(0)|答案(3)|浏览(150)

我知道我可以使用foreach在swift中迭代反射对象的子对象。

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循环。谢谢

von4xj4u

von4xj4u1#

类型Children实际上是AnyForwardCollection<Child>的typedef。
您不能用任何旧的Int索引到AnyForwardCollection。您需要使用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]
qq24tv8q

qq24tv8q2#

我想哈利·布鲁姆的答案,因为它是最优雅的方式,但它有一个错字:“i”必须是**“index”**,我添加了这一行,以实际获取给定索引处的项。

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!]
oprakyz7

oprakyz73#

在Kevins的回答之后,我将在Swift 3中稍微更新一下。

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

相关问题