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

时间:2016-05-15 11:16:53

标签: swift properties static

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

1 个答案:

答案 0 :(得分:0)

一种方法是实施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...
    ]
}

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