2015-01-13 51 views
8

是否有辦法在Swift中列出一個類的所有變量?如何在swift中列出一個類的所有變量

例如:

class foo { 
    var a:Int? = 1 
    var b:String? = "John" 
} 

我想列出這樣的:[a:1, b:"John"]

+0

神似(副本?)問題: [在swift中類的屬性列表](http://stackoverflow.com/questions/24844681/list-of-classs-properties-in-swift) –

+0

像這樣:http://stackoverflow.com/questions/24844681/list類中的屬性在迅速?哦 - 看起來如此:-) –

+0

我嘗試過但它不適合我,在我的情況下,我需要獲取變量而不是屬性。 –

回答

7

下應該使用反射來生成成員和值的列表。見小提琴在http://swiftstub.com/836291913/

class foo { 
    var a:Int? = 1 
    var b:String? = "John" 
} 
let obj = foo() 
let reflected = reflect(obj) 
var members = [String: String]() 
for index in 0..<reflected.count { 
    members[reflected[index].0] = reflected[index].1.summary 
} 
println(members) 

輸出:

[b: John, a: 1] 
+0

這個答案http://stackoverflow.com/a/24069875/1187415有一個鏈接到https://gist.github.com/mchambers/67640d9c3e2bcffbb1e2,其中(如果我理解正確)實際值被檢索,而不僅僅是字符串描述。 –

+0

這就是我需要的,謝謝傑森! –

+1

不知道。謝謝!如果寫成'for for index in 0 ..',則'for'會更「快速」。

7

如何在雨燕3.0遞歸地做到這一點:

import Foundation 

class FirstClass { 
    var name = "" 
    var last_name = "" 
    var age = 0 
    var other = "abc" 

    func listPropertiesWithValues(reflect: Mirror? = nil) { 
     let mirror = reflect ?? Mirror(reflecting: self) 
     if mirror.superclassMirror != nil { 
      self.listPropertiesWithValues(reflect: mirror.superclassMirror) 
     } 

     for (index, attr) in mirror.children.enumerated() { 
      if let property_name = attr.label as String! { 
       //You can represent the results however you want here!!! 
       print("\(mirror.description) \(index): \(property_name) = \(attr.value)") 
      } 
     } 
    } 

} 


class SecondClass: FirstClass { 
    var yetAnother = "YetAnother" 
} 

var second = SecondClass() 
second.name = "Name" 
second.last_name = "Last Name" 
second.age = 20 

second.listPropertiesWithValues() 

結果:

Mirror for FirstClass 0: name = Name 
Mirror for FirstClass 1: last_name = Last Name 
Mirror for FirstClass 2: age = 20 
Mirror for FirstClass 3: other = abc 
Mirror for SecondClass 0: yetAnother = YetAnother 
+0

'label'從ObjC轉換的類中以某種方式是零(例如FirstClass在ObjC中)。 – allenlinli

+0

此ObjC解決方案代替 https://stackoverflow.com/questions/13922581/is-there-a-way-to-log-all-the-property-values-of-an-objective-c-instance – allenlinli

0

也許有點晚了黨,但使用反射鏡和100%的工作該解決方案:

class YourClass : NSObject { 
    var title:String 
    var url:String 

    ...something other... 

    func properties() -> [[String: Any]] { 
     let mirror = Mirror(reflecting: self) 

     var retValue = [[String:Any]]() 
     for (_, attr) in mirror.children.enumerated() { 
      if let property_name = attr.label as String! { 
       retValue.append([property_name:attr.value]) 
      } 
     } 
     return retValue 
    } 
} 
在你的代碼

和地方...

var example = MoreRow(json: ["title":"aTitle","url":"anURL"]) 
print(example.listPropertiesWithValues()) 
相關問題