Mirror.handleChildren()

recursive reflections: inspect/manipulate on children's children.

๐Ÿ’พ ็จ‹ๅผ๏ผš 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

  1. (2022.01.27) - first version. (global function)

Last updated