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 oldFree plan: 30 tutor messages. Premium is unlimited.
