iterate over object class attributes in Swift

前端 未结 5 1978
星月不相逢
星月不相逢 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:50

    Here's Swift 5 version of object description:

    class TestClass: CustomStringConvertible {
    
        public var description: String {
            return Mirror(reflecting: self).children.compactMap({
                if let label = $0.label {
                    return "\(label): \($0.value)"
                }
                
                return ""
            }).joined(separator: "\n")
        }
    }
    

提交回复
热议问题