Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Swift Variable's Actual Name as String

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.

So this is basically what I want to do:

var appId: String? = nil  //This is true, since appId is actually the name of the var appId if( appId.getVarName = "appId"){     appId = "CommandoFurball" } 

Unfortunately I have not been able to find in apple docs anything that is close to this but this:

varobj.self or reflect(var).summary  

however, this gives information of what is inside the variable itself or the type of the variable in this case being String and I want the Actual name of the Variable.

like image 883
S.H. Avatar asked Sep 23 '14 22:09

S.H.


People also ask

How do you name a string variable?

String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.

How do you declare a string variable in Swift?

The var keyword is the only way to declare a variable in Swift. The most common and concise use of the var keyword is to declare a variable and assign a value to it. Remember that we don't end this line of code with a semicolon.


1 Answers

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

like image 173
Andrew Avatar answered Sep 30 '22 20:09

Andrew