3

I'm trying to get property information on an object in Swift. I've been able to get the names of the properties, and certain attributes, but I'm not sure how to extract the type of the property.

I've been trying to follow some of the suggestions on this objective-c related 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 possible yet in Swift? If so, how?

Community
  • 1
  • 1
Albert Bori
  • 9,832
  • 10
  • 51
  • 78
  • possible duplicate of [Does Swift support reflection?](http://stackoverflow.com/questions/24060667/does-swift-support-reflection) – Anthony Kong Aug 27 '14 at 00:25
  • Unfortunately, this is not a duplicate question of the above. The answer to that question is "Yes, sort of", but does not provide an answer for my more specific question. – Albert Bori Oct 26 '14 at 00:56

1 Answers1

0

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 must be NSObjects (or some other class that has enforces a default constructor.)

Albert Bori
  • 9,832
  • 10
  • 51
  • 78