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

Brent Royal-Gordon brent at architechies.com
Mon May 16 17:22:34 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?

No.

An enum case is something quite distinct from its raw value. If you just want a convenient way to write some particular value you use a lot, what you're looking for is a constant, not an enum.

> 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: { })
> }

For instance, in this case, you should just write something like:

	extension NSTimeInterval {
		static let fastTransition: NSTimeInterval = 0.15
		static let slowTransition: NSTimeInterval = 0.5
		
		static let fastAmbientAnimation: NSTimeInterval = 1.0
		static let slowAmbientAnimation: NSTimeInterval = 5.0
	}
	
	class Animate {
		static func fadeIn(view: UIView?, withSpeed duration: NSTimeInterval = .fastTransition) {
			...
			UIView.animateWithDuration(duration, animations: { })
		}
	}
	
	Animate.fadeIn(view, withSpeed: .fastTransition)
	Animate.fadeIn(view, withSpeed: .slowTransition)
	Animate.fadeIn(view, withSpeed: 3.14159)		// or anything else

Alternatively, if you really do want to lock people into either "fast" or "slow", then by all means use an enum. But realize that your new type is just that: a new type. It has its own semantic meaning, its own operations and methods and properties, and its own set of permitted values. It is not interchangeable with the raw value.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list