Swift protocol for string interpolation

cfischer picture cfischer · Sep 12, 2014 · Viewed 7.4k times · Source

What protocol do I have to implement to control the way an object is represented within a string interpolation in Swift?

I wan't to specify what get's printed in something like this:

struct A{

}

var a = A()
println("\(a)")

Answer

Mike S picture Mike S · Sep 12, 2014

You need to implement the Printable protocol:

This protocol should be adopted by types that wish to customize their textual representation. This textual representation is used when objects are written to an OutputStreamType.

protocol Printable {
    var description: String { get }
}

There's also the DebugPrintable protocol when it's only for debugging purposes:

This protocol should be adopted by types that wish to customize their textual representation used for debugging purposes. This textual representation is used when objects are written to an OutputStreamType.

protocol DebugPrintable {
    var debugDescription: String { get }
}

Documentation (Thanks @MartinR)

Note: As @Antonio and @MartinR mentioned in the comments, this doesn't work in the playground (as of Xcode6 GM anyway); that's a known bug. It does work in compiled apps.

From the Xcode6 GM Release Notes:

In Playgrounds, println() ignores the Printable conformance of user-defined types. (16562388)

As of Swift 2.0 Printable has now become CustomStringConvertible. Everything stays the same as before, you still need to implement

 var description: String { get }

But now its called CustomStringConvertible. And debug is CustomDebugStringConvertible