Greetings, traveler!
Developers have many tools for debugging, but we often use the print() function to output the value in the console. However, this is not too convenient in some cases. Consider this example.
struct Car {
let maxSpeed = 300
let horsepower = 350
}
let car = Car()
print(car)
Let’s check the console. Everything is quite detailed.
Car(maxSpeed: 300, horsepower: 350)
But let’s change the code a bit and turn our object into a class.
class Car {
let maxSpeed = 300
let horsepower = 350
}
let car = Car()
print(car)
After checking out the console, we will discover a disappointing output.
Car
But there is a way to print something more useful using the dump() function. Let’s explore the difference in the Apple documentation.
The dump() function:
Dumps the given object’s contents using its mirror to standard output.
The print() function:
Writes the textual representations of the given items into the standard output.
To illustrate the differences, let’s use the dump() and check out our console.
class Car {
let maxSpeed = 300
let horsepower = 350
}
let car = Car()
dump(car)
Car
- maxSpeed: 300
- horsepower: 350
Nice!
Conclusion
Both the print() and the dump() functions are handy. However, the dump() function may be a better choice when dealing with a reference type. And sure thing, remember that both of them are pretty expensive, so remember to remove them from the production code.