是否有等效于 C# 的“nameof()"函数来获取变量或成员名称的 Swift? [英] Is there a Swift equivalent of C#'s 'nameof()' function to get a variable or member's name?

查看:104
本文介绍了是否有等效于 C# 的“nameof()"函数来获取变量或成员名称的 Swift?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这里有一个关于 S/O 的现有问题,标题如下:

Swift:以字符串形式获取变量实际名称

顾名思义,这似乎正是我想要的.但是,查看已接受的答案(以及其他未接受的答案),他们指的是关键路径操作,这不是我所追求的.(即这不是重复的!)

就我而言,我希望一个变量的名称存储在第二个变量中输入字符串.

在 C# 中,使用 nameof 是微不足道的,就像这样...

int someVar = 3字符串 varName = nameof(someVar)//'varName' 现在保存字符串值 someVar";

<块引用>

注意:nameof() 在编译时执行,而不是在运行时执行,因此不需要反射或其他任何东西.编译器只是简单地代入变量的名称,就好像有人手动将其名称输入为字符串常量一样.

例如,当您想要定义一个查询对象时,它非常方便,您的成员名称与 URL 中传递的查询参数相匹配.

这是一个伪代码示例(即这显然不会编译,但显示了我所追求的.另外,请不要关注这个的 URL 方面.在实际代码中,我会使用 URLComponents,而不是字符串附加一个像这里的 URL.):

struct queryObject{让用户名:字符串让 highScore : Intvar getUrl:String{返回www.ScoreTracker.com/postScore?\(nameof(userName))=\(userName)&\(nameof(highScore))=\(highScore)"}}

以下是您将如何使用它以及它会返回什么:

let queryObject = QueryObject(userName:Maverick", highScore:123456)让 urlString = queryObject.getUrl

返回值为:

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

访问变量的字符串表示而不是使用字符串常量的优点很多:

  1. 没有硬编码的字符串.
  2. 您可以照常使用符号的重构/重命名和生成的字符串跟踪
  3. 允许您保持 API 和实现同步,这有助于提高可读性.

例如,假设 API 将查询参数从 userName 更改为 userId,您所要做的就是重构变量名称,输出将相应地更新,而无需必须手动触摸任何字符串.

那么,这可以在 Swift 中完成吗?你能得到实际的变量名并将其存储在第二个变量中吗?

解决方案

如果只处理 URL,建议使用 URLComponents,比较好.

型号:

struct QueryObject{var params = [字符串:字符串]()var getUrl: 字符串{let result = "www.ScoreTracker.com/postScore";守卫 var url = URL(string: result) else { return result}url.appendQueryParameters(params)返回 url.absoluteString}初始化(参数:[字符串:字符串]){self.params = 参数}}

然后:

 let params = ["userName": "Maverick", "highScore": "123456"]让 queryObject = QueryObject(params: params)让 urlString = queryObject.getUrlDDLog(urlString)//www.ScoreTracker.com/postScore?userName=Maverick&highScore=123456

Github 链接

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"

Note: nameof() executes at compile-time, not run-time so no reflection or anything else is needed. The compiler simply subs in the name of the variable as if someone manually typed its name as a string constant.

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. Also, please don't focus on the URL aspects of this. In real code I'd use URLComponents, not string-append a URL like here.):

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 many:

  1. No hard-coded strings.
  2. You can use refactoring/renaming of symbols as usual and the generated strings track
  3. Allows you to keep your API and implementation in sync which aids in readability.

For instance, say the API changed the query param from userName to userId, all one would have to do is refactor the variable name and the output would update accordingly without having to manually touch any strings.

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

解决方案

If you are only dealing with URLs, it is recommended to use URLComponents, which is better.

model:

struct QueryObject{

    var params = [String: String]()

    var getUrl: String{
        let result = "www.ScoreTracker.com/postScore"
        guard var url = URL(string: result) else { return result}
        url.appendQueryParameters(params)
        return url.absoluteString
    }

    init(params: [String: String]) {
        self.params = params
    }

}

then:

    let params = ["userName": "Maverick", "highScore": "123456"]
    let queryObject = QueryObject(params: params)
    let urlString = queryObject.getUrl
    DDLog(urlString) //www.ScoreTracker.com/postScore?userName=Maverick&highScore=123456

Github link

这篇关于是否有等效于 C# 的“nameof()"函数来获取变量或成员名称的 Swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆