如何列出swift中的类的所有变量 [英] How to list all Variables of a class in swift

查看:117
本文介绍了如何列出swift中的类的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to list all Variables of a class in Swift?

例如:

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

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

推荐答案

以生成成员和值的列表。请参阅 http://swiftstub.com/836291913/ 小提示

The following should use reflection to generate the list of members and values. See fiddle at 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]

这篇关于如何列出swift中的类的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆