"super" description for enums?

Not sure how to title this question. Start with an enum:

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 (which is not necessarily a bragging right imo).

If it were an super/sub type relationship, I'd call the "super" version. But I'm not sure how to get the "default stringification of an enum" in the my false branch, so that I can tune it for just the one distinct value.

In fact, by convention, enum cases should begin with lowercase letters, therefore, the normal way of implementing CustomStringConvertible would be…

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
}

extension UnitCode : CustomStringConvertible
{
  var description: String
  {
    switch self
    {
      case .unknown:
        return "Unknown"
      case .hz:
        return "Hz"
      case .gpm:
        return "GPM"
      case .m3_Hour:
        return "m³/hr"
      case .mA:
        return "mA"
      case .psi:
        return "PSI"
      case .bar:
        return "Bar"
    }
  }
}
1 Like

Fair enough... but is there no way to get the "default" implementation that is used to convert enums to strings so that it can be "customized/extended" in the description implementation. Let's say that they're all defined lowercase, but for some reason, I want to do a description that is "default description as uppercase". Of course I can just add another method that does that. But my real question is how I call the "base" algorithm.

1 Like

The only "base algorithm" is to literally "stringify" the enum case names. That is the reason why you need to implement CustomStringConvertible - which is an all or nothing affair.

It took me less than five minutes to do.

Unfortunately, you can't. The function you'd need to call is internal to the standard library. You'll need to provide a description for each case.

3 Likes

Thank you. That's the clarification I was looking for (though I secretly hoped the answer was otherwise).

And, don't forget, in this case, very few of the correctly spelt cases would have appeared with the correct string.

Related bug report: [SR-117] Calling default implementation of protocols · Issue #42739 · apple/swift · GitHub

(EDIT: meant this as a reply to @Travis_Griggs.)

This shouldn't be described as a bug; it's just not a feature provided by the language.

1 Like