comment 1

#1 Meaningful print debugging

Print debugging problems

Print debugging is simple and yet a powerful method. It is usually enough to toss a print() in a couple of places and a problem is recognised. As it works well for values and simple objects, when we print a more complex instance, the result is less informing.

To illustrate this, let’s take this simple Wheel class:

Struct benefits

Note that if Wheel was a struct and not a class we would already get a better print output:

Protocols come to rescue

But we do have some classes and that’s where usually protocols CustomStringConvertible for print() and CustomDebugStringConvertible for debugPrint() come in handy:

So now, if we print our wheel object after confoming to CustomStringConvertible and CustomDebugStringConvertible protocols then we get:

Neat!

UIViewControllers and NSObject inheritance

One of the least verbose print outputs belongs to UIViewController:

To make it simple, let’s just focus on CustomStringConvertible protocol and print() function. However, now if we try to conform to CustomStringConvertible protocol:

we receive an error "Redundant conformance of ‘WheelsViewController’ to protocol ‘CustomStringConvertible’"

That is because UIViewController inherits from NSObject that in turn conforms to NSObjectProtocol. We can see that all NSObject subclasses already implement description and optionally debugDescription properties:

To fix that issue we will override inherited properties.

Overriding inherited properties

As we are not satisfied with the default implementation of description property inherited from UIViewController, we can override it within the body of our WheelsViewController class or as an extension:

That’s it!

This post is inspired by Udacity course Xcode Debugging. It’s a great starting point in mastering your debugging skills. More advanced developers will also find it useful. Playground with the code from this post is available here.

1 Comment so far

  1. Art Kirillov

    HI guys! Thanks for your blog. Keep it up!

    Just as little compliment. When debugging I like to use dump() instead of print(). It may be more informative.

Leave a Reply


*