vendredi 15 juillet 2016

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.





Aucun commentaire:

Enregistrer un commentaire