How can I find the type of a property dynamically in swift (Reflection / Mirror)?

So, let's say I have a class like this:

class Employee: NSObject { var id: String? var someArray: [Employee]? } 

I use reflection to get property names:

 let employee = Employee() let mirror = Mirror(reflecting: employee) propertyNames = mirror.children.flatMap { $0.label } // ["businessUnitId", "someArray"] 

so good so far! Now I need to find out the type of each of these properties, so if I do employee.valueForKey("someArray") , this will not work, because it gives me only the AnyObject type. What would be the best way to do this? Especially for the array, I need to be able to dynamically report that the array contains an Employee type.

+5
source share
3 answers

You do not need to inherit from NSObject (unless you have a good reason).

 class Employee { var id: String? var someArray: [Employee]? } let employee = Employee() for property in Mirror(reflecting: employee).children { print("name: \(property.label) type: \(type(of: property.value))") } 

Output

 name: Optional("id") type: Optional<String> name: Optional("someArray") type: Optional<Array<Employee>> 

This also works with Structs.

+12
source
 employee.valueForKey("someArray")!.dynamicType 
0
source

If you inherit from NSObject , you can use some of the methods provided by NSCoding and Objective-C:

 let employee = Employee() employee.someArray = [] employee.valueForKey("someArray")?.classForCoder // NSArray.Type employee.valueForKey("someArray")?.classForKeyedArchiver // NSArray.Type employee.valueForKey("someArray")?.superclass // _SwiftNativeNSArrayWithContiguousStorage.Type 
0
source

All Articles