behnam27 behnam27 - 27 days ago 16
iOS Question

How to get class properties label in swift 3?

I want to get class properties label in runtime. for example,
I have this class:

class BasicD {
public var id_: Int64 = 0
public var a: Int32 = 0
public var c: NSData?
public var d: NSData?
}


I need to output to be: [id_,a,c,d]

I want somthing like reflection in java. I know mirror do like reflection, but for geting class properties in mirror I should initialize class first, but I do not want to do that.

Answer

You can use Mirror in swift3 to get all the properties of a class like this

class BasicD{
    public var id_: Int64 = 0
    public var a: Int32 = 0
    public var c: NSData?
    public var d: NSData?
}

let obj = BasicD()
var arrayOfObjects: [String] = []
let mirror =  Mirror(reflecting: obj)
for child in mirror.children {
    guard let key = child.label else { continue }
    arrayOfObjects.append(key)
    print(key)
}
print(arrayOfObjects)

Here arrayOfObjects contains all your variable name of class BasicD