P. Sami P. Sami - 1 year ago 99
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
, 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

Answer Source

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)")


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

This also works with Structs

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download