Mirror.handleChildren()
💾 程式: replit
// *: born, +: new, /: update
// ─────────────────────────────────────
// 2022.01.27 * (v.1) + handleChildren
// 2022.01.28 / handleChildren: global func -> Mirror method
extension Mirror {
/// ⭐ handle children of type T
public static func handleChildren<T>( // T: child's type ⭐
of subject : Any, // parent (⭐ of type `Any`)
type : T.Type, // child type
recursive : Bool = false, // first level only or all levels of children
with handler: (T)->Void) // child handler
{
// ⭐ mirror of `subject`
let mirror = Mirror(reflecting: subject)
// ⭐ do somethingfor each child.value of type `T`
// ⭐ for case let ... where
// ----------------------
// (pattern-match tuples + data binding + condition)
// ↱ ⭐ child.label ignored ╭── ⭐ where ───╮
for case let (_, value) in mirror.children where value is T {
// handle T value
handler(value as! T) // ⭐ force type casting (Any -> T)
// ⭐ handle children's T value recursively
if recursive {
handleChildren(of: value, type: T.self, recursive: true, with: handler)
}
}
}
}
History
(2022.01.27) - first version. (global function)
Last updated
Was this helpful?