Output will not be involved when implementing these two protocols in Playground and Swift REPL.

If you need to verify the code in this tip, you need to do it in a project.

When defining and implementing a type, a common and progressive way in Swift is defining a simple type first, and then adding features by conforming protocols by extension. This follows a good design concept and contributes to improving scalability. In Objective-C, we can use the combination of protocol and category to do similar things. It is even simpler in Swift.

Printable and DebugPrintable protocols are good example for it. For a regular object, when we use print on it, only the type of this object would be printed. If we need some more useful information, we can extend this type to make it conform Printable protocol. Consider we have a calendar app, in which some meeting appointments are stored. The model type contains the date, position and attendee name:

struct Meeting {
    var date: NSDate
    var place: String
    var attendeeName: String
}

let meeting = Meeting(date: NSDate(timeIntervalSinceNow: 86400),
                     place: "Room B1",
              attendeeName: "John")
print(meeting)
// Output:
// YourModuleName.Meeting

It is a meaningless output. What we need would be a formatted output, something like this:

print("Meeting with \(meeting.attendeeName) in \(meeting.place) at \(meeting.date)")
// Output:
// Meeting with John in Room B1 at 2014-08-25 11:05:28 +0000

Much better! But it is not acceptable as well if we need to write the log statement every time. Proper way to do this is using Printable protocol, defining a template string for every print calling. Compared change the Meeting struct, we prefer an extension on it, to avoid messing up the core model with the helper methods:

extension Meeting: Printable {
    var description: String {
        return "Meeting with \(meeting.attendeeName) in \(meeting.place) at \(meeting.date)"
    }
}

Now, we can just simply pass the meeting to print to get the formatted output:

print(meeting)
// Output:
// Meeting with John in Room B1 at 2014-08-25 11:05:28 +0000

DebugPrintable is similar to Printable, except it will only called in a debugger logout. For these types conforming to DebugPrintable, we can use a printing command, such as po meeting, to print the debugDescription string defined in its DebugPrintable.