做一个假设:
struct A{ var a:String; var b:Int }
Run Code Online (Sandbox Code Playgroud)
我如何制作for循环或其他方法来获取结构A中的变量名称?
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/
| 归档时间: |
|
| 查看次数: |
2969 次 |
| 最近记录: |