用于字符串插值的 Swift 协议 [英] Swift protocol for string interpolation
问题描述
我必须实现什么协议来控制对象在 Swift 中的字符串插值中的表示方式?
What protocol do I have to implement to control the way an object is represented within a string interpolation in Swift?
我不想指定像这样打印的内容:
I wan't to specify what get's printed in something like this:
struct A{
}
var a = A()
println("\(a)")
推荐答案
你需要实现Printable
协议:
希望自定义其的类型应采用此协议文字表示.这种文本表示用于对象被写入 OutputStreamType
.
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
OutputStreamType
.
protocol Printable {
var description: String { get }
}
还有 DebugPrintable
协议仅用于调试目的:
There's also the DebugPrintable
protocol when it's only for debugging purposes:
希望自定义的类型应采用此协议它们用于调试目的的文本表示.这将对象写入到文本中时使用文本表示OutputStreamType
.
This protocol should be adopted by types that wish to customize their textual representation used for debugging purposes. This textual representation is used when objects are written to an
OutputStreamType
.
protocol DebugPrintable {
var debugDescription: String { get }
}
文档(感谢@MartinR)
Documentation (Thanks @MartinR)
注意:正如评论中提到的@Antonio 和@MartinR,这在操场上不起作用(无论如何从Xcode6 GM 开始);这是一个已知的错误.它确实适用于已编译的应用程序.
Note: As @Antonio and @MartinR mentioned in the comments, this doesn't work in the playground (as of Xcode6 GM anyway); that's a known bug. It does work in compiled apps.
来自 Xcode6 GM 发行说明:
From the Xcode6 GM Release Notes:
在 Playgrounds 中,println() 忽略了 Printable 一致性用户定义的类型.(16562388)
In Playgrounds, println() ignores the Printable conformance of user-defined types. (16562388)
从 Swift 2.0 开始,Printable
现在变成了 CustomStringConvertible
.一切都和以前一样,你仍然需要实现
As of Swift 2.0 Printable
has now become CustomStringConvertible
. Everything stays the same as before, you still need to implement
var description: String { get }
但现在它被称为 CustomStringConvertible.并且调试是 CustomDebugStringConvertible
But now its called CustomStringConvertible. And debug is CustomDebugStringConvertible
这篇关于用于字符串插值的 Swift 协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!