Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Swift中,如何获得变量的完全限定名?_Swift_Reflection_Types_Mirror - Fatal编程技术网

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

在Swift中,如何获得变量的完全限定名?,swift,reflection,types,mirror,Swift,Reflection,Types,Mirror,在名为“MyApp”的应用程序中考虑此代码 class Foo{ class Laa{ static let laaVar = "I am laaVar" } } 我知道我可以得到Laa的完全限定名,就像这样 let laaName = String(reflecting: Foo.Laa.self) // Returns 'MyApp.Foo.Laa' 但是我怎样才能获得laaVar(例如“MyApp.Foo.Laa.laaVar”)的完全限定名呢 这可能吗

在名为“MyApp”的应用程序中考虑此代码

class Foo{
    class Laa{
        static let laaVar = "I am laaVar"
    }
}
我知道我可以得到Laa的完全限定名,就像这样

let laaName = String(reflecting: Foo.Laa.self)
// Returns 'MyApp.Foo.Laa'
但是我怎样才能获得
laaVar
(例如“MyApp.Foo.Laa.laaVar”)的完全限定名呢

这可能吗

奖金问题

给定上面的代码和一个包含字符串“MyApp.Foo.Laa.laaVar”的变量,如何获得值“I am laaVar”


我猜这两个问题的答案都与反射/镜像有关。

我想我找到了解决你问题的方法。您可以使用Objective-c运行时,尤其是函数
class\u copyPropertyList
,它描述了类声明的属性。例如:

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 ?? "")")
    }
}
<代码>导入基础 福班{ Laa类:NSObject{ @objc static let laaName=“我是laaVar” } } 变量计数:CUnsignedInt=0 让methods=class\uCopyPropertyList(object\uGetClass(Foo.Laa.self),&count)! 对于0中的i..<计数{ 让selector=property_getName(methods.advanced(by:Int(i)).pointee) 如果let key=String(cString:selector,编码:.utf8){ 设res=Foo.Laa.value(forKey:key) 打印(“名称:\(键),值:\(res??)”) } } 结果是:

姓名:laaName,价值观:我是laaVar


有趣!在投票通过之前,让我先考虑一下。(顺便说一句,我更正了问题中的代码,并相应地更新了您的答案。纯粹是命名上的更改。)尽管如此,还是快速提问。。。你为什么只做
Int(i)
,而不做
i
?它不是已经从
for
循环中暗示为
Int
类型吗?@MarqueIV我必须转换这样的Int,因为:
错误:无法将类型“CUnsignedInt”(又名“UInt32”)的值转换为预期的参数类型“Int”
HA!我不知道它把隐式循环变量当作UInt32处理!有趣!