mardi 19 décembre 2017

How can you get the string-representation of a variable's name in Swift

Ok, there's an existing question here on S/O with the following title:

Swift: Get Variable Actual Name as String

By it's name, it seems that's exactly what I want. However, looking at the accepted answer (and the other non-accepted ones), they are referring to key path manipulation, which isn't what I'm after. (i.e. This is not a duplicate!)

In my case, I want the name of one variable to be stored in a second variable of type string.

In C#, this is trivial using nameof, like so...

int someVar = 3

string varName = nameof(someVar)
// 'varName' now holds the string value "someVar"

This I believe happens at compile-time so no reflection or anything else is needed at run-time. It simply subs in the name of the variable.

It's pretty handy when you, for instance, want to define a query object where your member names match the query parameters passed in a URL.

Here's a pseudo-code example (i.e. this clearly won't compile, but shows what I'm after):

struct queryObject{

    let userName  : String
    let highScore : Int

    var getUrl:String{
        return "http://ift.tt/2yY8JZ9"
    }
}

Here's how you'd use it and what it would return:

let queryObject = QueryObject(userName:"Maverick", highScore:123456)

let urlString = queryObject.getUrl

The return value would be:

http://ift.tt/2BdWq0F

The advantages of this are:

  1. The names of your members are used as the query parameters keeping the struct's usage clean and simple
  2. There's no need to define constants to hold the query parameter names since they are implicit from the member names
  3. You get full refactoring support of actual symbols, not find-replace of strings

For instance, if I simply refactored userName to be userId, the output would now be...

http://ift.tt/2yYBbtO

...without me having to change any string constants.

So, can this be done in Swift? Can you get the actual variable name and store it in a second variable?





Aucun commentaire:

Enregistrer un commentaire