【问题标题】:How to list all Variables of a class in swift如何快速列出类的所有变量
【发布时间】:2015-01-13 17:46:25
【问题描述】:

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

例如:

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

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

【问题讨论】:

标签: class variables swift


【解决方案1】:

如何在 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

【讨论】:

【解决方案2】:

下面应该使用反射来生成成员和值的列表。参见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]

【讨论】:

【解决方案3】:

聚会可能有点晚了,但是这个使用反射和镜像的解决方案是 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())

【讨论】:

    【解决方案4】:

    我从这里得到了线索。 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
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      相关资源
      最近更新 更多