Is there an easy way to iterate the attributes of a class in Swift.
That is, I have a Person class, which has 3 attributes: name ,lastname,age.
Is there something similar
for attribute in Person {
println("\(attribute): \( attribute.value)")
}
The output will be for example:
name: Bob
lastname: Max
age: 20
They have removed the reflection in Swift 2.0. This is my enumerated attribute And value method.
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 mir rored_object.children.enumerated() {
if let property_name = attr.label as String! {
print("Attr \(index): \(property_name) = \(attr.value)")< br /> }
}
Output: Attr 0: name = user name Attr 1: last_name = user lastname Attr 2: age = 20
< /div>
Is there an easy way to iterate the attributes of a class in Swift.
That is, I have a Person class, which has 3 attributes: name, lastname,age.
Is there something similar
for attribute in Person {
println("\(attribute): \(attribute .value)")
}
The output will be for example:
name: Bob
lastname: Max
age: 20
They have removed reflection in Swift 2.0. This is how I enumerate properties and values.
< p>
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_o bject.children.enumerate() {
if let property_name = attr.label as String! {
print("Attr \(index): \(property_name) = \(attr.value)")< br /> }
}
// 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