Skip to content

Commit 7336581

Browse files
authored
Merge pull request #9 from jVirus/astemir-mirror-extension
Mirror+ReflectProperties extension
2 parents 7efbc54 + c358443 commit 7336581

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import Foundation
2+
3+
extension Mirror {
4+
/**
5+
This static method iterates over properties of a given object, applying a closure to each property that matches the specified type.
6+
7+
- Parameters:
8+
- target: The object whose properties will be reflected.
9+
- type: The type of properties to which the closure should be applied. By default, it's `T.self`.
10+
- recursively: If set to `true`, the method will reflect properties of the target's properties recursively. Default value is `false`.
11+
- closure: The closure to apply to each property of the specified type. The closure takes a parameter of type `T`.
12+
13+
- Note: This function uses **Swift's Mirror API** for reflection. Not all properties may be accessible for types that do not fully support reflection.
14+
15+
Exmaple usage:
16+
```
17+
class MyClass {
18+
var myIntProperty: Int = 0
19+
var myStringProperty: String = "Hello"
20+
}
21+
22+
let myInstance = MyClass()
23+
Mirror.reflectProperties(of: myInstance, matchingType: Int.self) { property in
24+
print("The value of myIntProperty is (property)")
25+
}
26+
```
27+
*/
28+
public static func reflectProperties<T>(
29+
of target: Any,
30+
matchingType type: T.Type = T.self,
31+
recursively: Bool = false,
32+
using closure: (T) -> Void
33+
) {
34+
let mirror = Mirror(reflecting: target)
35+
36+
for child in mirror.children {
37+
(child.value as? T).map(closure)
38+
guard recursively else { continue }
39+
40+
Mirror.reflectProperties(
41+
of: child.value,
42+
recursively: true,
43+
using: closure
44+
)
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)