用于字符串插值的Swift协议

cfi*_*her 12 protocols string-interpolation swift

我必须实现什么协议来控制Swift中字符串插值中对象的表示方式?

我不想用这样的东西来指定得到的东西:

struct A{

}

var a = A()
println("\(a)")
Run Code Online (Sandbox Code Playgroud)

Mik*_*e S 23

您需要实现Printable协议:

希望定制其文本表示的类型应采用此协议.当对象被写入时,使用该文本表示OutputStreamType.

protocol Printable {
    var description: String { get }
}
Run Code Online (Sandbox Code Playgroud)

DebugPrintable当它仅用于调试目的时,还有协议:

希望定制用于调试目的的文本表示的类型应采用此协议.当对象被写入时,使用该文本表示 OutputStreamType.

protocol DebugPrintable {
    var debugDescription: String { get }
}
Run Code Online (Sandbox Code Playgroud)

文档(感谢@MartinR)

注意:正如评论中提到的@Antonio和@MartinR,这在游乐场中无效(无论如何都是Xcode6 GM); 这是一个已知的错误.它在编译的应用程序中有效.

来自Xcode6 GM发行说明:

在Playgrounds中,println()忽略用户定义类型的Printable一致性.(16562388)

截至Swift 2.0 Printable现已成为CustomStringConvertible.一切都和以前一样,你仍然需要实施

 var description: String { get }
Run Code Online (Sandbox Code Playgroud)

但现在它被称为CustomStringConvertible.调试是CustomDebugStringConvertible