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

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

问题描述:

所以我试图在 Swift 中将实际变量名称作为字符串获取,但还没有找到这样做的方法......或者我可能正在以一个不好的角度看待这个问题和解决方案.

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.

根据更新自 这个答案,它Swift 3 通过 #keyPath

As per the updated from this answer, it is supported in Swift 3 via #keyPath

NSPredicate(format: "%K == %@", #keyPath(Person.firstName), "Andrew")