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)
}
}
}
}โฌ๏ธ ้่ฆ๏ผ Logger
ๅท่ก็ตๆ๏ผ
Pattern Matching - pattern-match on mirror's children.
for case let ... where - (pattern matching + binding + condition)
if let ... as? - optional binding.
(... as? ...)?.method() - optional chaining.
... as! ... - force type casting.
Logger is used in [๐็ฏไพ].
History
(2022.01.27) - first version. (global function)
้ๅ็จๅผ็ขผๆ่ฉฒ่ฆๅฏซๆ global function๏ผๅฆๆๅฏซๆ protocol method ๆๅบ็พ่จฑๅคๅ้ก (ไพๅฆ๏ผchildren of children ๅฏ่ฝๆ นๆฌไธ้ตๅพช้ๅ protocol๏ผๅฐ่ด็กๆณไฝฟ็จๆญค method recursively)
๐ ๐พ ็จๅผ๏ผ attemp 1 (with lots of errors)
Last updated
Was this helpful?