Start with an enum in Swift:
enum UnitCode:UInt {
case Unknown = 0
case Hz = 1
case GPM = 2
case M3_Hour = 3
case mA = 4
case PSI = 5
case Bar = 6
}
For most of those, an expression like:
let text = "\(aUnitCode)"
will produce a nice result, since the printed form matches the code form (e.g. .Hz == "Hz").
But for the M3_Hour
, I'd like to print that as m³/hr
. So conform to CustomStringConvertable
, right? I figured the following would not work:
extension UnitCode: CustomStringConvertible {
var description:String {
return self == .M3_Hour ? "m³/hr" : String(describing: self)
}
}
It did not. Infinite recursion. Thought so. But Swift often surprises me (in both good and bad ways).
If the enum were a super/sub type relationship, I'd call the "super" version of description to get the "default" text rendering of the enum. But I'm not sure how to get the "default stringification of an enum" in my false branch, so that I can tune it for just the one distinct value. Is there a way to do this?