gbertb
9/28/2016 - 3:21 PM

Use auto-describing objects with CustomStringConvertible

Use auto-describing objects with CustomStringConvertible

extension CustomStringConvertible {
    var description : String {
        var description: String = ""
        if self is AnyObject {
            description = "***** \(self.dynamicType) - <\(unsafeAddressOf((self as! AnyObject)))>***** \n"
        } else {
            description = "***** \(self.dynamicType) *****\n"
        }
        let selfMirror = Mirror(reflecting: self)
        for child in selfMirror.children {
            if let propertyName = child.label {
                description += "\(propertyName): \(child.value)\n"
            }
        }
        return description
    }
}

class Dog : CustomStringConvertible {
    let name: String
    let age: Int
    let color: String
    
    init (name: String, age: Int, color: String) {
        self.name = name
        self.age = age
        self.color = color
    }
}

let bronoTheDog = Dog(name: "Brono", age: 4, color: "Brown")
let wendyTheDog = Dog(name: "Wendy", age: 2, color: "White")
print(bronoTheDog)
print(wendyTheDog)