[swift-evolution] [Idea] Typed Numerics

Karl razielim at gmail.com
Mon Aug 22 12:20:08 CDT 2016


> On 22 Aug 2016, at 18:17, Charlie Monroe via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I've personally come across something like Nur suggested. In particular, this is with NSTimeInterval, which is a typedef for Double.
> 
> What I wanted to do is to make
> 
> extension NSTimeInterval {
> 	static let minute: NSTimeInterval = 60.0
> 	static let hour: NSTimeInterval = 3600.0
> 	/// ... day, ...
> }
> 
> and you can then use it NSTimeInterval.minute.
> 
> The issue now is that is polutes the Double type as well, so currently, it's valid to write Double.minute with the code above - which is not disirable behavior IMHO.
> 
> Sure, you can work around by introducing e.g. enum or an empty struct TimeIntervals with static members, but I personally think that making specialized subtypes of numeric types is a good way to introduce some constants while not poluting the entire namespace.
> 
> Or maybe it's me still thinking too much in C-style and the proper way would be to represent NSTimeInterval as a different type...

In that particular case I would say NSTimeInterval should be a struct with convenient initialisers. Similarly to DispatchTime(Interval).

Have you seen the new Foundation Measurement API? http://oleb.net/blog/2016/07/measurements-and-units/

Karl


More information about the swift-evolution mailing list