Start learning free

LESSON 612 OF 640 · OBJECT-ORIENTED PROGRAMMING

Printing Objects in Swift in Swift

Lesson

TL ; DR:

Make your class adopt CustomStringConvertible and give it a description. Then print shows that text for the object.


class Cat {
    var name: String
    init(name: String) { self.name = name }
}

extension Cat: CustomStringConvertible {
    var description: String {
        return "Cat named \(name)"
    }
}

// print(Cat(name: "Tom")) prints Cat named Tom


Full lesson:

Swift turns an object into text before it prints it. For a class, it only knows the module and class name by default:

main.Cat

That tells you nothing about the cat.

CustomStringConvertible is a protocol with one property, description. When a type adopts it, print uses its description. So does interpolation, as in "I have \(tom)".

description is a computed property. It stores nothing. Its code runs each time something reads it, and it returns the text.

Here the protocol comes in an extension. An extension adds code to a type that already exists. You could also write class Cat: CustomStringConvertible and put description in the class.


Your task

The Dog class below has a name and an age. Below it, add an extension that makes Dog adopt CustomStringConvertible.

Its description returns the name, then " is ", the age and " years old". The code in mainFunction prints two dogs.

Expected output:

Rex is 3 years old
Bella is 5 years old
STEP 1 OF 3
    Ctrl + Enter to check

    Printing Objects in Swift

    Keep going with Swift500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free