How can I change the textual representation displayed for a type in Swift?

Swift 2 – 4

Summary

Conform to the CustomStringConvertible protocol and add description:

var description: String {
    return "description here"
}

Example

You can create some structs:

struct Animal : CustomStringConvertible {
    let type : String

    var description: String {
        return type
    }
}

struct Farm : CustomStringConvertible {
    let name : String
    let animals : [Animal]

    var description: String {
        return "\(name) is a \(self.dynamicType) with \(animals.count) animal(s)."
    }
}

If you initialize them:

let oldMajor = Animal(type: "Pig")
let boxer = Animal(type: "Horse")
let muriel = Animal(type: "Goat")

let orwellsFarm = Farm(name: "Animal Farm", animals: [oldMajor, boxer, muriel])

The custom descriptions will appear in your playground:

enter image description here

See also CustomDebugStringConvertible, which you can use for more verbose output during debugging.


Usage Note

You can initialize a String from any type without implementing this protocol. For example:

enter image description here

For this reason, the docs say:

Using CustomStringConvertible as a generic constraint, or accessing a conforming type’s description directly, is therefore discouraged.

Leave a Comment