Looking for a Swift equivalent of Cocoa's description
, I found the following protocols in Swift: Printable
and DebugPrintable
.
What's the difference between these two protocols and when should I use each one?
Here is an example class
class Foo: Printable, DebugPrintable {
var description: String {
return "Foo"
}
var debugDescription: String {
return "debug Foo"
}
}
This is how to use it.
println(Foo())
debugPrintln(Foo())
Here is the output with no surprises:
Foo
debug Foo
I didn't try this in a Playground. It works in an actual project.
The answer above was for Swift 1. It was correct at the time.
Update for Swift 2.
println and debugPrintln are gone and the protocols have been renamed.
class Foo: CustomStringConvertible, CustomDebugStringConvertible {
var description: String {
return "Foo"
}
var debugDescription: String {
return "debug Foo"
}
}
print(Foo())
debugPrint(Foo())
In Xcode 6 Beta (Version 6.2 (6C101)) I find that both println and debugPrintln use description if-and-only-if the class descends from NSObject. I don't see that either uses debugDescription at all but when run in a Playground debugPrintln outputs only to the Console and doesn't appear in the playground itself.
import Foundation
class Tdesc: NSObject, Printable, DebugPrintable {
override var description: String {return "A description"}
override var debugDescription: String {return "A debugDescription"}
}
class Xdesc: Printable, DebugPrintable {
var description: String {return "A description"}
var debugDescription: String {return "A debugDescription"}
}
let t = Tdesc()
let x = Xdesc()
t.description
let z: String = "x\(t)"
println(t) // Displays "A description" in the Playground and Console
debugPrintln(t) // Displays nothing in the Playground but "A description" in the Console
x.description
let y: String = "x\(x)"
println(x) // Displays "__lldb_expr_405.Xdesc" in the Playground and Console
debugPrintln(x)
I believe the main difference is the property that's used to print. Printable
has description
and DebugPrintable
has debugDescription
:
https://stackoverflow.com/a/24254220/887210
Edit:
Apparently print() and println() don't work properly with Printable and DebugPrintable:
struct TestPrintable : Printable {
var description: String { return "Testing Printable" }
}
struct TestDebugPrintable : DebugPrintable {
var debugDescription: String { return "Testing DebugPrintable" }
}
println(TestPrintable()) // -> "__lldb_expr_42.TestPrintable"
println(TestDebugPrintable()) // -> "__lldb_expr_42.TestDebugPrintable"
More information about this:
http://vperi.com/2014/06/04/textual-representation-for-classes-in-swift/