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??
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With