[swift-evolution] Could enums have their rawValue type inferred?

Eric Miller hi at simple.gy
Fri May 13 13:09:01 CDT 2016


This might open a larger can of worms than I imagine, but what do you folks
think about using the `rawValue` of an enum when that rawValue is a fit for
the expected type?

Use case.

I'm making an animation facade, and it has some speed presets:

class Animate {
  enum transitionSpeed: NSTimeInterval {
    case fast = 0.15
    case slow = 0.5
  }
  enum ambientAnimationSpeed: NSTimeInterval {
    case fast = 1.0
    case slow = 5.0
  }
  ...
}

I did them with static variables at first but that made the call site
verbose. Compare:

Animate.fadeIn(view, withSpeed: Animate.cfg.transitionFast)
Animate.fadeIn(view, withSpeed: .fast)

So, I like the enum approach better, but my library code has to use
`rawValue` to do anything with the actual value, of course:

static func fadeIn(view: UIView?, withSpeed duration:transitionSpeed =
.fast) {
  ...
  UIView.animateWithDuration(duration.rawValue, animations: { })
}

It's not a serious issue, but the code is more clear and beautiful if it
has just myIntent, rather than myIntent.rawValue.

I've hit this issue when modeling other things, such as:

* server fault codes
* HTTP status codes
* Currency codes
* Days of the week

Would it be appropriate to "autocast" to the rawValue of the enum when the
rawValue's Type matches the type expectation of the API? Or would this
introduce a bunch of type system uncertainty?

Maybe this could be implemented as a protocol? It feels almost like the
convenience of `CustomStringConvertible`'s `description` property.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160513/c7c83773/attachment.html>


More information about the swift-evolution mailing list