如何在swift中列出类的所有变量

时间:2015-01-13 17:46:25

标签: class variables swift

有没有办法在Swift中列出类的所有变量?

例如:

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

我想这样列出:[a:1, b:"John"]

4 个答案:

答案 0 :(得分:14)

如何以递归方式在Swift 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 {
                //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

答案 1 :(得分:8)

以下内容应使用反射来生成成员和值列表。请参阅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]

答案 2 :(得分:1)

派对可能有点迟了,但使用反射和镜像的解决方案是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())

答案 3 :(得分:0)

我从这里得到了线索。 https://medium.com/@YogevSitton/use-auto-describing-objects-with-customstringconvertible-49528b55f446

这是Swift 4.0以上的演示。

import Foundation

extension CustomStringConvertible {
    var description : String {
        var description: String = ""
        if self is AnyObject {  // unsafeAddressOf((self as! AnyObject))
            description = "***** \(type(of: self)) - <\(Unmanaged.passUnretained(self as AnyObject).toOpaque())>***** \n"
        } else {
            description = "***** \(type(of: self)) *****\n"
        }
        let selfMirror = Mirror(reflecting: self)
        for child in selfMirror.children {
            if let propertyName = child.label {
                description += "\(propertyName): \(child.value)\n"
            }
        }
        return description
    }
}

extension NSObject {
    var description: String {
        var description: String = ""
        if self is AnyObject {  // unsafeAddressOf((self as! AnyObject))
            description = "***** \(type(of: self)) - <\(Unmanaged.passUnretained(self as AnyObject).toOpaque())>***** \n"
        } else {
            description = "***** \(type(of: self)) *****\n"
        }
        let selfMirror = Mirror(reflecting: self)
        for child in selfMirror.children {
            if let propertyName = child.label {
                description += "\(propertyName): \(child.value)\n"
            }
        }
        return description
    }
}

class AA: CustomStringConvertible {
    var a: String = "aaa"
}

class BB: NSObject {
    var b: String = "bbb"
}

let  aa = AA()
print(aa)

let  bb = BB()
print(bb.description)

输出-

***** AA - <0x00000001001038e0>***** 
a: aaa

***** BB - <0x0000000100103310>***** 
b: bbb