Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you print a Swift object (po) in lldb?

In Objective-C, when you NSLog an object or po it in lldb, the object receives the description message.

In Swift however, the behaviour seems to be different. I implemented both Printable (requires description property) and DebugPrintable (which requires in turn a property named debugDescription). If I try to println() an object or po it, none of those properties gets called.

What's going on? What are those protocols for then??

like image 201
cfischer Avatar asked Sep 26 '14 14:09

cfischer


1 Answers

There's a known issue that Printable is ignored by the Swift REPL (i.e., anything in a Playground or run by xcrun swift at the command line) but recognized by the compiler (compiled apps in the simulator or xcrun swiftc).

For example, here's the code of "foo.swift":

struct Person : Printable {
    let name: String

    var description: String {
        return "\(name)"
    }
}

let me = Person(name: "Nate")
println(me)

If I run it using the REPL, I get this:

$ xcrun swift foo.swift 
foo.Person

But if I compile it first, and then run it, it uses the description computed property:

$ xcrun -sdk macosx swiftc foo.swift ; ./foo
Nate

The DebugPrintable protocol is useful if you want to be able to use the debugPrint and debugPrintln functions -- in compiled code, they print out an instance's debugDescription property.

like image 120
Nate Cook Avatar answered Sep 19 '22 17:09

Nate Cook