環境
- Swift: 5.2.2
- Xcode: 11.4.1
プロパティ名を取得する
for children in Mirror(reflecting: self).children {
print(children)
}
- Mirrorという構造体に参照したいオブジェクトや構造体を渡す
- 各プロパティは、
children
から参照できる
サンプル
class MyClass {
var hoge: Int = 0
var fuga: String = ""
func getProperties() {
for children in Mirror(reflecting: self).children {
print(children)
}
}
}
struct MyStruct {
var hoge: Int = 0
var fuga: String = ""
func getProperties() {
for children in Mirror(reflecting: self).children {
print(children)
}
}
}
print("MyClass properties")
let c = MyClass()
c.getProperties()
print("MyStruct properties")
let s = MyStruct()
s.getProperties()
出力
MyClass properties
(label: Optional("hoge"), value: 0)
(label: Optional("fuga"), value: "")
MyStruct properties
(label: Optional("hoge"), value: 0)
(label: Optional("fuga"), value: "")
- プロパティ名は、
label
というプロパティで参照できる
- 値は、
value
というプロパティで参照できる