如何修改在字符串插值中显示的文本输出?
Printable
协议(protocol)看起来最明显,但它在字符串插值和打印实例时都被忽略了,例如:
struct Point : Printable
{
var x = 0
var y = 0
var description : String {
return "(\(x), \(y))"
}
func toString() -> String {
return description
}
}
同样 toString()
约定也没有效果:
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)
PlayGround 的行为又有所不同,它使用自己的字符串表示结构,即:
p // {x 10, y 20}
有什么方法可以更改实例的显示方式?
最佳答案
swift 2 - 4
总结
符合CustomStringConvertible
协议(protocol)并添加description
:
var description: String {
return "description here"
}
例子
您可以创建一些结构:
struct Animal : CustomStringConvertible {
let type : String
var description: String {
return type
}
}
struct Farm : CustomStringConvertible {
let name : String
let animals : [Animal]
var description: String {
return "\(name) is a \(self.dynamicType) with \(animals.count) animal(s)."
}
}
如果你初始化它们:
let oldMajor = Animal(type: "Pig")
let boxer = Animal(type: "Horse")
let muriel = Animal(type: "Goat")
let orwellsFarm = Farm(name: "Animal Farm", animals: [oldMajor, boxer, muriel])
自定义描述将出现在您的 playground 中:
另请参阅 CustomDebugStringConvertible
,您可以在调试期间使用它来获得更详细的输出。
使用说明
您可以从任何类型不实现此协议(protocol)来初始化String
。例如:
出于这个原因,文档说:
Using
CustomStringConvertible
as a generic constraint, or accessing a conforming type'sdescription
directly, is therefore discouraged.
关于swift - 如何在 Swift 中更改为某个类型显示的文本表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24068506/