如何在 Swift 中更改为类型显示的文本表示? [英] How can I change the textual representation displayed for a type in Swift?
问题描述
如何修改在字符串插值中显示的文本输出?
How can I modify the textual output that gets displayed in string interpolation?
Printable
协议看起来最明显,但它在字符串插值和打印实例时都被忽略,例如:
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
}
}
同样,toString()
约定也没有效果:
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)
在 PlayGround 中的行为再次不同,它使用自己的字符串表示结构,即:
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?
推荐答案
Swift 2 - 4
总结
符合CustomStringConvertible
协议并添加description
:
var description: String {
return "description here"
}
<小时>
示例
您可以创建一些结构:
Example
You can create some structs:
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 中:
The custom descriptions will appear in your playground:
另见 CustomDebugStringConvertible
,您可以在调试期间使用它来获得更详细的输出.
See also CustomDebugStringConvertible
, which you can use for more verbose output during debugging.
您可以从任何类型初始化一个String
,而无需实现此协议.例如:
You can initialize a String
from any type without implementing this protocol. For example:
出于这个原因,文档说:
For this reason, the docs say:
因此不鼓励使用 CustomStringConvertible
作为通用约束,或直接访问符合类型的 description
.
Using
CustomStringConvertible
as a generic constraint, or accessing a conforming type'sdescription
directly, is therefore discouraged.
这篇关于如何在 Swift 中更改为类型显示的文本表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!