Swift 2 - 4
Summary
Conform to the CustomStringConvertible
protocol and add 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)."
}
}
If you initialize them:
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])
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:
Using CustomStringConvertible
as a generic constraint, or accessing a conforming type's description
directly, is therefore discouraged.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…