Jason Jason - 4 years ago 201
Swift Question

What is the Swift equivalent of -[NSObject description]?

In Objective-C, one can add a

method to their class to aid in debugging:

@implementation MyClass
- (NSString *)description
return [NSString stringWithFormat:@"<%@: %p, foo = %@>", [self class], foo _foo];

Then in the debugger, you can do:

po fooClass
<MyClass: 0x12938004, foo = "bar">

What is the equivalent in Swift? Swift's REPL output can be helpful:

1> class MyClass { let foo = 42 }
3> let x = MyClass()
x: MyClass = {
foo = 42

But I'd like to override this behavior for printing to the console:

4> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)

Is there a way to clean up this
output? I've seen the

/// 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 `OutputStream`.
protocol Printable {
var description: String { get }

I figured this would automatically be "seen" by
but it does not appear to be the case:

1> class MyClass: Printable {
2. let foo = 42
3. var description: String { get { return "MyClass, foo = \(foo)" } }
4. }
6> let x = MyClass()
x: MyClass = {
foo = 42
7> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)

And instead I have to explicitly call description:

8> println("x = \(x.description)")
x = MyClass, foo = 42

Is there a better way?

Answer Source

Through some experimentation I have discovered that the Printable and DebugPrintable protocols work when compiling an actual app, but not in the REPL or Playground.

Side Note: The code you wrote is correct, but in this case, you are probably looking for DebugPrintable

Swift has renamed these protocols to be CustomStringConvertible and CustomDebugStringConvertible - though the compiler currently helpfully tells you it's done that :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download