本文介绍了Swift 变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能找出变量名,我叫它什么,而变量有一个值?
Is it possible to find out the variable name, what I called it, while the variable has a value?
所以我的意思是:
var varName: Int
...
if ((varName == "varName") && (varName == 6)) {
...
}
这可能吗?
Is this possible?
推荐答案
看看下面 Swift
示例中的 Reflection
take a look about Reflection
in Swift
example below
struct Car {
let type: CarType
let name: String
init(_ type: CarType, name: String) {
self.type = type
self.name = name
}
}
enum CarType {
case Sport
case Economics
}
let bmw = Car(CarType.Sport, name: "BMW")
let bmwMirror = Mirror(reflecting: bmw)
let children = bmwMirror.children
print("car properties: \(children.count)") //2
var generator = children.generate()
let type = generator.next()
print(type!.label) // type Optional
print(type!.value) //Sport
let name = generator.next()
print(name!.label) // name Optional
print(name!.value) //BMW
注意:我在 Swift 1.2 中使用 Swift 2.0 Xcode beta 7 使用 let bmwMirror = reflect(bmw)
并且您可以访问属性 bmwMirror.[indexOfProperty].1(.value or label)
Note : I am using Swift 2.0 Xcode beta 7 in Swift 1.2 use let bmwMirror = reflect(bmw)
and you can access the properties bmwMirror.[indexOfProperty].1(.value or label)
这篇关于Swift 变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!