Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 the property names:

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

so far so good! Now i need to be able to figure out the type of each of these properties, so if I do the employee.valueForKey("someArray"), it won't work because it only gives me the AnyObject type. What would be the best way to do this? Specially for the array, I need to be able to dynamically tell that the array contains type of Employee.

like image 444
P. Sami Avatar asked Jul 15 '16 14:07

P. Sami


1 Answers

You don't need to inherit from NSObject (unless you have a good reason to).

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

like image 152
Luca Angeletti Avatar answered Sep 29 '22 12:09

Luca Angeletti