Is there a Swift equivalent of C#'s 'nameof()' function to get a variable or member's name?

房东的猫 提交于 2019-12-23 10:11:30

问题


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"

I believe this happens at compile-time, not run-time so no reflection or anything else is needed, nor do the symbol names have to be in the executable. The compiler 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 "www.ScoreTracker.com/postScore?\(nameof(userName))=\(userName)&\(nameof(highScore))=\(highScore)"
    }
}

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:

www.ScoreTracker.com/postScore?userName=Maverick&highScore=123456

The advantages of having access to a string representation of a variable, instead of using string constants 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, say the API changed the query param from userName to userId. All I would have to do is refactor my member name accordingly and the output would now be...

www.ScoreTracker.com/postScore?userId=Maverick&highScore=123456

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

Note: The above example is just for simple, illustrative purposes of one way you could use a variable's name. It is not how we would actually handle managing URLs, nor adding query parameters to them; a discussion which would be too verbose, and off-topic for this post.

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

来源:https://stackoverflow.com/questions/47891310/is-there-a-swift-equivalent-of-cs-nameof-function-to-get-a-variable-or-mem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!