Get Property Names of Object in Swift

Here is an extension for NSObject that will return the names of the properties in the object.

import Foundation

extension NSObject {

    //
    // Retrieves an array of property names found on the current object
    // using Objective-C runtime functions for introspection:
    // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
    //
    func propertyNames() -> Array<String> {
        var results: Array<String> = [];

        // retrieve the properties via the class_copyPropertyList function
        var count: UInt32 = 0;
        var myClass: AnyClass = self.classForCoder;
        var properties = class_copyPropertyList(myClass, &count);

        // iterate each objc_property_t struct
        for var i: UInt32 = 0; i < count; i++ {
            var property = properties[Int(i)];

            // retrieve the property name by calling property_getName function
            var cname = property_getName(property);

            // covert the c string into a Swift string
            var name = String.fromCString(cname);
            results.append(name!);
        }

        // release objc_property_t structs
        free(properties);

        return results;
    }

}

This extension makes use of the introspection functions in Objective-C to retreive the property struct and pluck out the names.

Usage is fairly simple:

var properties: Array<String> = myNSObj.propertyNames()  

And it is a great utility for performing Key/Value operations.

var properties = someObj.propertyNames();

for property in properties {  
   var value: AnyObject? = someObj.valueForKey(property);
   self.setValue(value, forKey: property)
}
comments powered by Disqus