Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

iterate over object class attributes in Swift

Is there a Simple way in Swift to iterate over the attributes of a class.

i.e. i have a class Person, and it has 3 attributes: name, lastname, age.

is there something like

for attribute in Person {
     println("(attribute): (attribute.value)")
}

the output would be for example:

name: Bob
lastname: Max
age: 20
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They have removed reflect within Swift 2.0. This is how I am enumerating attributes and values.

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 later
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...