Belvi Nosakhare
Belvi Nosakhare

Reputation: 3255

get Child of Mirror.Children by index

I understand I can iterate through the children of a reflected object in swift using 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)
}

Is it possible to access the child by index . Like

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

How can i access each child by index without using the for loop. Thanks.

Upvotes: 2

Views: 1185

Answers (3)

Harry Bloom
Harry Bloom

Reputation: 2449

Further from Kevins answer, I will update slightly for 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)

Upvotes: 2

wider-spider
wider-spider

Reputation: 515

I'd like the answer of Harry Bloom, because it is the most elegant way, but is has a typo: "i" must be "index" and I added the line to actually get the item at the given 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!]

Upvotes: 2

Kevin
Kevin

Reputation: 17566

The type Children is actually a typedef for AnyForwardCollection<Child>.

You can't index into an AnyForwardCollection with any old Int. You need to use an AnyForwardIndex. You can use startIndex to get the starting index and advancedBy() to move forward.

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]

Upvotes: 4

Related Questions