[swift-evolution] Support for newtype feature/typesafe calculations
John Randolph
jcr at mac.com
Thu Jan 7 08:52:47 CST 2016
> On Jan 7, 2016, at 4:06 AM, James Campbell via swift-evolution <swift-evolution at swift.org> wrote:
>
> So this is how this feature could be achieved right now with minimal changes to the language.
>
> - We expose some kind of protocol that allows you to Box up types, we could call this `Box` or something else like `Unit`. (I have a working implementation in the current language with a bit of boilerplate). This protocol handles the default implementation of converting from literals and to floats etc.
> - For each type-safe unit for a calculation - you define a protocol extending this `Box` type which defines the associated type of the value that unit holds. For example for Degree and Radian I declared a `AngleType` which set the associated type to be a double.
> - For each unit type, you declare a struct that inherits from that protocol you defined. So I have two structs `Degree` and `Radian` which implement the `AngleType` protocol.
> - You implement the functions for figuring out if your units are equal and all other operators they may need i.e `Degree(360) - 30`.
I took a different approach to this, which was to typealias Angle to Double, keep all Angles as radians (since the stdlib trig functions take radians), and add some computed setters and getters to let me access an Angle in radians, degrees, or grads.
I would like to see Angle, along with several other basic geometric concepts, promoted to the Swift standard library.
-jcr
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160107/00be032b/attachment.html>
More information about the swift-evolution
mailing list