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?
Comments about style and work arounds appreciated. The answer I was looking for came from the Swift Forums and was as simple as:
Unfortunately, you can't. The function you'd need to call is internal to the standard library.
So basically, the machinery that does the fallback conversion from enums to their as-coded-strings when you don't provide your own description
implementation is not available.
(Which @matt also said in the comments, and if he'd made that an answer, I would have added even more points to his vast surplus of reputation)