Logo 61e73bc61c0e1780102320e879dc3cac0e29303ea8894dd8f10c942f3ba8120f


An adorable little blog

Print It How You Like It in Swift

Sunday — April 24th, 2016

Vw beetle

Sometimes the normal debug description just doesn't cut it for your custom types. It's handy to have a little more information when you call print or description. It can speed up debugging and help others understand what is happening with your custom types. It's also super quick and easy to add this extra information into your types.

If you've been with Swift since the early days you may have heard of the Printable protocol which allows for this very thing. Printable has been superseded by CustomStringConvertible in Swift 2.

To make your own custom types conform to CustomStringConvertible you only need to implement description as a computed property:

struct CarCompany: CustomStringConvertible {
    var name: String
    var isPassingEmissions: Bool
    var description: String {
        return "CarCompany: \(name), is 
\( isPassingEmissions ? "totally" : "not")
passing emissions. You can trust us.
Nothing to see here." } }

And now when you ask for a struct or object's description, you get back the information you want others to see.

let vw = CarCompany(name: "Volkswagon",
isPassingEmissions: true) print(vw)
// CarCompany: Volkswagon, is totally passing emissions.
// You can trust us. Nothing to see here.