[swift-users] Restricting associated values

Travis Griggs travisgriggs at gmail.com
Mon Jun 19 09:40:34 CDT 2017

> On Jun 18, 2017, at 10:33 PM, Howard Lovatt via swift-users <swift-users at swift.org> wrote:
> To me Angle is a unit with two common representations: radians and degrees. It's not an enum because it doesn't have two values, it has one value that you can view in two ways.
> Therefore I would make an Angle struct, something like:
> <snip>

Lots of different ways I think. I chose not between struct and enum, but used both:

struct Angle {
	enum Unit:CGFloat {
		case radians = 1.0
		case degrees = 57.29577951309314 // 360.0 / Tau
		case rotations = 0.1591549430918953 // 1.0 / Tau
	// MARK: - Stored Properties
	var raw:CGFloat = 0.0
	var unit:Unit = .radians
        // MARK: - Left for the Student

I do a bit of UI programming with angles and have found rotations (I’ve drunk too much of the Tau manifesto koolaid probably) to be the most natural fit for a lot of things. Having an angle object allows me to layer over (via extensions) the various cocoa/uikit apis that take angles with type safe angle objects, and yet given me the ability to express said angles in whatever intermediate domain best fits.

More information about the swift-users mailing list