IOS How to get the type of a property of an object in Swift?
I am trying to get information about the properties of an object in Swift. I was able to get the property names and some attributes, but I'm not sure how to get the property type.
I am trying to follow some suggestions on this objective-c post
class func classOfProperty(parentType: AnyClass, propertyName: String) -> AnyClass?
{
var type: AnyClass?
var property: objc_property_t = class_getProperty(parentType, propertyName);
var attributes = NSString(UTF8String: property_getAttributes(property)).componentsSeparatedByString(",") as [String]
if(attributes.count > 0) {
?????
}
return type
}
Is this still possible in Swift? If so, how?
+3
source to share
1 answer
In swift 1.2, the following is possible:
import Foundation
func getPropertyType(parentType: NSObject.Type, propertyName: String) -> Any.Type? {
var instance = parentType()
var mirror = reflect(instance)
for i in 0..<mirror.count {
var (key, valueInfo) = mirror[i]
if key == propertyName {
return valueInfo.valueType
}
}
return nil
}
enum EyeColor: Int { case Brown = 1, Blue = 2, Black = 3, Green = 4 }
class Person: NSObject {
var name = "Fred"
var eyeColor = EyeColor.Black
var age = 38
var jumpHeight: Float?
}
println(getPropertyType(Person.self, "name"))
println(getPropertyType(Person.self, "eyeColor"))
println(getPropertyType(Person.self, "age"))
println(getPropertyType(Person.self, "jumpHeight"))
Unfortunately they have to be NSObjects (or some other class that uses the default constructor.)
0
source to share