NEW! Master Swift design patterns with my latest book! >>

How to create a custom debug description

Paul Hudson       @twostraws

Swift lets you print all types of data, but some data is more useful than others thanks to the CustomDebugStringConvertible protocol. If you write a type conforming to that protocol, you must include a debugDescription string property that describes how instances of this type should be represented while debugging.

To test this out, we’re going to create a Player struct that stores a player’s name. When we try to debug an instance of this struct – i.e., print it out, or hover over it in the debugger – we just want the player’s name to come back, for easier debugging.

Try adding this struct to a playground:

struct Player: CustomDebugStringConvertible {
    var name: String = "@twostraws"

    var debugDescription: String {
        return name
    }
}

You can now create instances of that struct and print them out to see the player name:

let player = Player()
print(player)

Available from iOS 8.0 – learn more in my book Pro Swift

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Upgrade to the premium experience

Get all 40 projects in PDF and ePub, plus exclusive content that will take your Swift learning to the next level – buy the Hacking with Swift book today!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>