如何在swift中获取结构中的变量名?

季亨达*_*季亨达 0 swift

做一个假设:

struct A{ var a:String; var b:Int }
Run Code Online (Sandbox Code Playgroud)

我如何制作for循环或其他方法来获取结构A中的变量名称?

Jam*_*hen 8

Mirror是Swift中反射的类(它实际上是一个结构).下面是枚举结构属性的一个非常简单的示例.

let a = A(a: "abc", b: 1)
let mirror = Mirror(reflecting: a)
for child in mirror.children {
    print(child.label!)
    print(child.value)
}
Run Code Online (Sandbox Code Playgroud)

输出将是:

a
abc
b
1
Run Code Online (Sandbox Code Playgroud)

发现Swift Reflection API的帖子值得一读:https://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/

  • 我也是这么想的!但它实际上运行速度慢了 3.5 倍![链接](https://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/) 这没什么大不了的,但它实际上创造了大量的内存使用与上面代码几乎相同的代码时也会泄漏。Apple 没有记录的一个问题,但当用作许多 Structs 遵守的协议时,它最终使我的应用程序陷入困境。 (2认同)