P. Sami P. Sami - 4 months ago 18
Swift Question

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
.

Answer

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: \(property.value.dynamicType)")
}

Output

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

This also works with Structs