[swift-evolution] Epic: Typesafe calculations

Tino Heth 2th at gmx.de
Sun Dec 27 04:56:33 CST 2015


> There’s some unfortunate extra boilerplate here, which could be better handled with newtype support in the language, but when compiled with optimizations the resulting code is nearly identical to using plain Ints.

Cool — have you checked the generated assembler for this conclusion? But I guess there is some knowledge on how to build an optimizing compiler in the core team ;-), so I'd expect little to no penalty (I guess the memory footprint of plain Ints is still better).
I have been playing with something similar, but using enums instead of structs (I thought it's nice to model different units for the same quantity).
With generics and protocols, it is already possible to do simple calculations without to much overhead, and maybe I'll create a library for the most important physical quantities with this toolset.

I'm still trying to figure out if there is a clever trick to model compound units (velocity as m/s, for example) in a general way:
It is simple to express that UnitA * UnitB is equal to UnitB * UnitA, but it gets tedious when there are many units and factors…

Tino


More information about the swift-evolution mailing list