简体   繁体   English

在Swift中,如何获得变量的完全限定名称?

[英]In Swift, how do you get the fully-qualified name of a variable?

Consider this code in an app called 'MyApp'... 在名为“MyApp”的应用中考虑此代码...

class Foo{
    class Laa{
        static let laaVar = "I am laaVar"
    }
}

I know I can get the fully-qualified name of Laa , like so... 我知道我可以得到完全合格的Laa名字,就像这样......

let laaName = String(reflecting: Foo.Laa.self)
// Returns 'MyApp.Foo.Laa'

but how can I get the fully-qualified name of laaVar (eg "MyApp.Foo.Laa.laaVar")? 但是如何获得laaVar的完全限定名称(例如“MyApp.Foo.Laa.laaVar”)?

Is that even possible? 这甚至可能吗?

Bonus Question 奖金问题

Given the above code, and a variable containing the string "MyApp.Foo.Laa.laaVar", how can I get the value "I am laaVar"? 鉴于上面的代码,以及包含字符串“MyApp.Foo.Laa.laaVar”的变量,我如何获得值“我是laaVar”?

I'm guessing the answer to both has something to do with reflection/mirroring. 我猜两个答案都与反射/镜像有关。

I think I found a solution for your question. 我想我找到了一个解决你问题的方法。 You might use the Objective-c runtime, especially the function class_copyPropertyList which describes the properties declared by a class. 您可以使用Objective-c运行时,尤其是函数class_copyPropertyList ,它描述了类声明的属性。 Example: 例:

import Foundation

class Foo {
    class Laa: NSObject {
        @objc static let laaName = "I am laaVar"
    }
}

var count: CUnsignedInt = 0
let methods = class_copyPropertyList(object_getClass(Foo.Laa.self), &count)!
for i in 0 ..< count {
    let selector = property_getName(methods.advanced(by: Int(i)).pointee)
    if let key = String(cString: selector, encoding: .utf8) {
        let res = Foo.Laa.value(forKey: key)
        print("name: \(key), value: \(res ?? "")")
    }
}

the result is: 结果是:

name: laaName, value: I am laaVar name:laaName,value:我是laaVar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM