在 Swift中是否有一种简单的方法来迭代类的属性. 即我有一个Person类,它有3个属性:name,lastname,age. 是否有类似的东西 for attribute in Person { println("\(attribute): \(attribute.value)")} 输出将是例如
即我有一个Person类,它有3个属性:name,lastname,age.
是否有类似的东西
for attribute in Person { println("\(attribute): \(attribute.value)") }
输出将是例如:
name: Bob lastname: Max age: 20他们已经删除了Swift 2.0中的反射.这就是我枚举属性和值的方式.
class People { var name = "" var last_name = "" var age = 0 } var user = People() user.name = "user name" user.last_name = "user lastname" user.age = 20 let mirrored_object = Mirror(reflecting: user) // Swift 2 for (index, attr) in mirrored_object.children.enumerate() { if let property_name = attr.label as String! { print("Attr \(index): \(property_name) = \(attr.value)") } } // Swift 3 and after for (index, attr) in mirrored_object.children.enumerated() { if let property_name = attr.label as String! { print("Attr \(index): \(property_name) = \(attr.value)") } }
Output: Attr 0: name = user name Attr 1: last_name = user lastname Attr 2: age = 20