2015-01-13 1 views
8

Swift에서 클래스의 모든 변수를 나열하는 방법이 있습니까? 예를 들어클래스의 모든 변수를 신속하게 나열하는 방법

는 :

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

나는이처럼 나열 할 : [a:1, b:"John"]

+0

매우 유사 (중복?) 질문 : [신속한 클래스 속성 목록] (http://stackoverflow.com/questions/24844681/list-of-classs-properties-in-swift) –

+0

이렇게 : http://stackoverflow.com/questions/24844681/list -of-class-properties-in-swift? 오 - 그렇게 보인다 :-) –

+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 of 0 ..'과 같이 쓰여진다면 더 "swifty"합니다

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()) 
관련 문제