It’s now or never

IT系の技術ブログです。気になったこと、勉強したことを備忘録的にまとめて行きます。

【Swift 5.x】クラス/構造体のプロパティ名を取得する

環境

  • 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というプロパティで参照できる