iterate over object class attributes in Swift

前端 未结 5 1988
星月不相逢
星月不相逢 2020-11-30 01:28

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

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 01:39

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

提交回复
热议问题