You need to conform to the CustomStringConvertible
protocol. Then you implement the description
property.
class MyClass: CustromStringConvertible {
var i: Int
var j: Int
// ...
var description: String {
return "\(i), \(j)"
}
}
var mc = MyClass(5, 10)
print(mc) // 5, 10
From the Apple documentation:
Types that conform to the CustomStringConvertible protocol can provide their own representation to be used when converting an instance to a string. The String(describing:) initializer is the preferred way to convert an instance of any type to a string. If the passed instance conforms to CustomStringConvertible, the String(describing:) initializer and the print(_:) function use the instance’s custom description property.
Accessing a type’s description property directly or using CustomStringConvertible as a generic constraint is discouraged.
For debugging purposes, you might want to conform to CustomDebugStringConvertible
and implement debugDescription
instead (documentation).
This would look like this (Playground file):
import Foundation
struct Point {
let x: Int, y: Int
}
extension Point: CustomStringConvertible {
var description: String {
return "NON-DEBUG - (\(x), \(y))"
}
}
extension Point: CustomDebugStringConvertible {
var debugDescription: String {
return "DEBUG - (\(x), \(y))"
}
}
let p = Point(x: 21, y: 30)
print(p)
// NON-DEBUG - (21, 30)
print(String(reflecting: p))
// DEBUG - (21, 30)