如何在Swift中获取所有静态属性

如何在Swift中获取所有静态属性

class AllDevice: Reflectable{

    static let LIGHT_ONOFF_NH_3A_R11_01_L12 = "LIGHT_ONOFF_NH_3A_R11_01_L12"

    static let PLUG_ONOFF_NH_3A_R11_01_B2AC = "PLUG_ONOFF_NH_3A_R11_01_B2AC"
    static let PLUG_POWER_NH_3A_R11_01_B2AC="PLUG_POWER_NH_3A_R11_01_B2AC"
    static let PLUG_ENERGY_NH_3A_R11_01_B2AC="PLUG_ENERGY_NH_3A_R11_01_B2AC"

    static let PLUG_ONOFF_NH_3A_R11_02_B2B8="PLUG_ONOFF_NH_3A_R11_02_B2B8"
    static let PLUG_POWER_NH_3A_R11_02_B2B8="PLUG_POWER_NH_3A_R11_02_B2B8"
    static let PLUG_ENERGY_NH_3A_R11_02_B2B8="PLUG_ENERGY_NH_3A_R11_02_B2B8"

    static let  PLUG_ONOFF_NH_3A_R11_03_B2D2="PLUG_ONOFF_NH_3A_R11_03_B2D2"
    static let PLUG_POWER_NH_3A_R11_03_B2D2="PLUG_POWER_NH_3A_R11_03_B2D2"
    static let PLUG_ENERGY_NH_3A_R11_03_B2D2="PLUG_ENERGY_NH_3A_R11_03_B2D2"

}
如何在Swift中获取所有静态属性?
我试过下面的文章,但没用
How to list all Variables of a class in swift

最佳答案

一种方法是实现CustomReflectable

class AllDevice: CustomReflectable {

    static let LIGHT_ONOFF_NH_3A_R11_01_L12 = "LIGHT_ONOFF_NH_3A_R11_01_L12"

    static let PLUG_ONOFF_NH_3A_R11_01_B2AC = "PLUG_ONOFF_NH_3A_R11_01_B2AC"
    static let PLUG_POWER_NH_3A_R11_01_B2AC="PLUG_POWER_NH_3A_R11_01_B2AC"
    static let PLUG_ENERGY_NH_3A_R11_01_B2AC="PLUG_ENERGY_NH_3A_R11_01_B2AC"

    static let PLUG_ONOFF_NH_3A_R11_02_B2B8="PLUG_ONOFF_NH_3A_R11_02_B2B8"
    static let PLUG_POWER_NH_3A_R11_02_B2B8="PLUG_POWER_NH_3A_R11_02_B2B8"
    static let PLUG_ENERGY_NH_3A_R11_02_B2B8="PLUG_ENERGY_NH_3A_R11_02_B2B8"

    static let PLUG_ONOFF_NH_3A_R11_03_B2D2="PLUG_ONOFF_NH_3A_R11_03_B2D2"
    static let PLUG_POWER_NH_3A_R11_03_B2D2="PLUG_POWER_NH_3A_R11_03_B2D2"
    static let PLUG_ENERGY_NH_3A_R11_03_B2D2="PLUG_ENERGY_NH_3A_R11_03_B2D2"

    func customMirror() -> Mirror {
        return Mirror(self, children: [
            "LIGHT_ONOFF_NH_3A_R11_01_L12": self.dynamicType.LIGHT_ONOFF_NH_3A_R11_01_L12,
            "PLUG_ONOFF_NH_3A_R11_01_B2AC": self.dynamicType.PLUG_ONOFF_NH_3A_R11_01_B2AC,
            "PLUG_POWER_NH_3A_R11_01_B2AC": self.dynamicType.PLUG_POWER_NH_3A_R11_01_B2AC
            // etc...
        ])
    }
}

let device = AllDevice()
let m = Mirror(reflecting: device)
// you can access m.children now

如你所见,这并不有趣,而且涉及很多字符串文字。如果更改分配给每个设备类型的值,则必须相应地更新镜像。
它将设备类型常量实现为enum
enum Device: String {
    case LIGHT_ONOFF_NH_3A_R11_01_L12 = "LIGHT_ONOFF_NH_3A_R11_01_L12"
    case PLUG_ONOFF_NH_3A_R11_01_B2AC = "PLUG_ONOFF_NH_3A_R11_01_B2AC"
    case PLUG_POWER_NH_3A_R11_01_B2AC = "PLUG_POWER_NH_3A_R11_01_B2AC"
    // etc..

    static let allDevices: [Device] = [
        .LIGHT_ONOFF_NH_3A_R11_01_L12,
        .PLUG_ONOFF_NH_3A_R11_01_B2AC,
        .PLUG_POWER_NH_3A_R11_01_B2AC
        // etc...
    ]
}

这样,编译器就可以提供一些错误检查。

08-05 21:11