2016-05-15 67 views
1
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

你的問題不清楚,你想達到什麼目的?你想輸出每一個變量是嗎?編輯您的答案並顯示示例輸出應該如何。 – Anokrize

回答

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... 
    ] 
} 

這樣的編譯器可以爲您提供一些錯誤檢查。

相關問題