2

Is there a way to get the compile time name of a variable in Swift 2? I mean the first variable name, which references to a new class instance, if any.

Here is a simple example:

public class Parameter : FloatLiteralConvertible {
   var name:String?
   var value:Double
   // init from float literal
   public required init (floatLiteral value: FloatLiteralType) {
      self.value = Double(value)
      self.name = getLiteralName()
   }
   func getLiteralName () -> String {
      var literalName:String = ""
      // do some magic to return the name
      return literalName
   }
}

let x:Parameter = 2.0
print(x.value)  // this returns "2.0"
print(x.name!)  // I want this to return "x"

I've already checked similar questions on that topic handling mirroring or objective-c reflections. But in all those cases, one can get only the property names in a class - in the example above name and value.

The same question has been asked in 2014 - Swift: Get Variable Actual Name as String - and I hope, that since then there is a solution in swift 2.

Community
  • 1
  • 1
dundee
  • 33
  • 3

1 Answers1

3

No, there is no way to do that.

You have to understand that in the compiled state that variable usually does not exist. It can be optimized out or it is represented only as an item on the execution stack.

Even in languages with much better reflection that Swift has, usually you cannot inspect local variables.

To be honest, getting the name of a local variable dynamically has no practical use case.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Thank you, good to know. The practical use in my case would be to make a math framework more user friendly when the user declares the variables. I need to store variable names and it would have been nice, if I could get the source code literal as the default name. Of course, writing `let x=Parameter("x",2)` is always an option, but not so elegant. – dundee Apr 29 '16 at 19:33
  • @dundee The problem is that once you write `let y = x` your idea breaks. And what about returning a parameter from a function? Then the variable is unnamed... – Sulthan Apr 29 '16 at 19:40