Get a Swift Variable's Actual Name as String

This is officially supported in Swift 3 using #keyPath()

https://github.com/apple/swift-evolution/blob/master/proposals/0062-objc-keypaths.md

Example usage would look like:

NSPredicate(format: "%K == %@", #keyPath(Person.firstName), "Wendy")

In Swift 4 we have something even better: \KeyPath notation

https://github.com/apple/swift-evolution/blob/master/proposals/0161-key-paths.md

NSPredicate(format: "%K == %@", \Person.mother.firstName, "Wendy")

// or

let keyPath = \Person.mother.firstName
NSPredicate(format: "%K == %@", keyPath, "Andrew")

The shorthand is a welcome addition, and being able to reference keypaths from a variable is extremely powerful


As per the updated from this answer, it is supported in Swift 3 via #keyPath

NSPredicate(format: "%K == %@", #keyPath(Person.firstName), "Andrew")

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