How can I modify the textual output that gets displayed in string interpolation?
The Printable
protocol looks the most obvious but it's ignored in both String Interpolation and when printing the instance, e.g:
struct Point : Printable
{
var x = 0
var y = 0
var description : String {
return "(\(x), \(y))"
}
func toString() -> String {
return description
}
}
Likewise the toString()
convention has no effect either:
var p = Point(x: 10, y: 20)
println(p) // V11lldb_expr_05Point (has 2 children)
println("\(p)") // V11lldb_expr_05Point (has 2 children)
println(p.description) // (10, 20)
println("\(p.description)") // (10, 20)
The behavior is different again in PlayGround which uses its own String representation for structs, i.e:
p // {x 10, y 20}
Is there a way I can change how an instance is displayed?
Relevant Apple Swift Docs
Apple provides this example:
If you try this in playground, you will get the same issue that you're getting (
V11lldb_expr...
). In playground, you get the description on the right hand side when you call the initializer, but theprintln
doesn't return something legible.Out of playground, however, this code behaves as you would expect. Both your code and the sample code from Apple above print the correct
description
when used in a non-playground context.I don't think you can change this behavior in playground. It could also just be a bug.
EDIT: I'm pretty sure that this is a bug; I submitted a bug report to Apple.
UPDATE: In Swift 2, instead of
Printable
, useCustomStringConvertible
(relevant doc link).This appears to be a bug in the playground. If you actually compile and run the programme normally it prints:
as expected.
You should report this at https://bugreport.apple.com
As an alternative in Swift 5+ you can extend the String.StringInterpolation
This will change the value for
print("\(p)")
but not forprint(p)
- which will still use the descriptionIf you open the console view : View -> Assistant Editor -> Show Assistant Editor you can see expected print lines Checked in xCode 6.3.2 with Yosimite 10.10
Swift 2 - 4
Summary
Conform to the
CustomStringConvertible
protocol and adddescription
:Example
You can create some structs:
If you initialize them:
The custom descriptions will appear in your playground:
See also
CustomDebugStringConvertible
, which you can use for more verbose output during debugging.Usage Note
You can initialize a
String
from any type without implementing this protocol. For example:For this reason, the docs say: