Get a Swift Variable's Actual Name as String

后端 未结 6 2042
借酒劲吻你
借酒劲吻你 2020-11-29 04:40

So I am trying to get the Actual Variable Name as String in Swift, but have not found a way to do so... or maybe I am looking at this problem and solution in a bad angle.

6条回答
  •  悲哀的现实
    2020-11-29 05:13

    This is my solution

    class Test { 
        var name: String = "Ido"
        var lastName: String = "Cohen"
    }
    
    let t = Test()
    let mirror = Mirror(reflecting: t)
    
    for child in mirror.children {
        print(child.label ?? "")
    }
    

    print will be

    name
    lastName
    

提交回复
热议问题