13

I have a model class that contains some static variables and properties. In Runtime I can get the properties;

let instance = entity.init()

let mirror = Mirror(reflecting:instance)

var propertyStrings = [String]()

for (propertyName, childMirror) in mirror.children {

}

But I want to get static variables of the class as a list too. So how can I get the list of static variable's names and values ? Here is my model class' structure :

class ActionModel: NSObject {

static let kLastModified = "LastModified"
static let kEntityName = "EntityName"
static let kIdentifier = "Id"


var lastModified: Int64
var entityName: String?
var identifier : PrimaryKeyString

2 Answers2

18

Getting type properties via reflection is not supported yet. You can see this by inspecting the displayStyle of the Mirror you get if you pass the class object to the initializer:

let mirror = Mirror(reflecting: ActionModel.self)
print(mirror.displayStyle)    // nil
Alberto Doda
  • 281
  • 2
  • 6
9

You might use the Objective-c runtime, especially the function class_copyPropertyList which describes the properties declared by a class. Example:

import Foundation

class Foo:NSObject {
    @objc static var prop1: String? = "Hello I am prop1!"
    @objc static var prop2: String? = "Hello I am prop2!"
}

var count: CUnsignedInt = 0
let methods = class_copyPropertyList(object_getClass(Foo.self), &count)!
for i in 0 ..< count {
    let selector = property_getName(methods.advanced(by: Int(i)).pointee)
    if let key = String(cString: selector, encoding: .utf8) {
        let res = Foo.value(forKey: key)
        print("name: \(key), value: \(res ?? "")")
    }
}
mugx
  • 9,869
  • 3
  • 43
  • 55