0

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.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
behnam27
  • 241
  • 2
  • 4
  • 11

1 Answers1

3

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

Rajat
  • 10,977
  • 3
  • 38
  • 55