<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body dir="auto"><div><br></div><div>On Jun 18, 2017, at 19:30, Nevin Brackett-Rozinsky via swift-users &lt;<a href="mailto:swift-users@swift.org">swift-users@swift.org</a>&gt; wrote:<br><br></div><blockquote type="cite"><div><div dir="ltr">Is there a way to restrict the associated values of an enum? For example, suppose I have this type:<div><br></div><div><div><font face="monospace, monospace">enum Angle {</font></div><div><font face="monospace, monospace">&nbsp; &nbsp; case radians(Double)</font></div><div><font face="monospace, monospace">&nbsp; &nbsp; case degrees(Double)</font></div><div><font face="monospace, monospace">}</font></div></div><div><br></div><div>I want to ensure that the radians values is always in [0, 2π) and the degrees values is always in [0, 360). Ideally I would like to write an initializer which is called when the user writes eg. “let x: Angle = .degrees(-45)” and contains the logic to wrap the provided value into the allowed range (in this case by adding a multiple of 360).</div><div><br></div><div>I don’t see a way to do it.&nbsp;Is this possible?<br></div><div><br></div><div>The closest I’ve found is to create auxiliary types such as</div><div><br></div><div><font face="monospace, monospace">struct Degree { … }</font></div><div><font face="monospace, monospace">struct Radian { … }</font><br></div><div><br></div><div>and give them appropriate initializers, then use them for the associated values. However that is undesirable because it adds an extra level of depth to get at the actual numeric values.</div><div><br></div><div>Is there a better way?</div></div></div></blockquote><br><div>Not off the top of my head, at least not without changing the syntax.</div><div><br></div><div>You could add two inits, with different argument labels, and not directly set the case: <span style="background-color: rgba(255, 255, 255, 0);">“let x = Angle(degrees: -45)”</span></div><div><br></div><div>You could add "public var radians: Double { get {...} set {...} }" (and again for "degrees") to `Angle`. The getter would need to<span style="background-color: rgba(255, 255, 255, 0);">&nbsp;switch on self to figure out if you need to convert between the two (like if someone said ".radians(2).degrees"):&nbsp;“var x = Angle.radians(0); x.degrees = -45"</span></div><div><br></div><div><span style="background-color: rgba(255, 255, 255, 0);">Alternately, you could add "subscript() -&gt; Double"&nbsp;and switch on self in both the setter and the getter to figure out if you should be wrapping at&nbsp;2π or 360 and to do any conversions:&nbsp;“var x: Angle = .radians(0); x[] = -45"</span></div><div><span style="background-color: rgba(255, 255, 255, 0);"><br></span></div><div><span style="background-color: rgba(255, 255, 255, 0);">Hope that helps</span></div><div><span style="background-color: rgba(255, 255, 255, 0);">- Dave Sweeris&nbsp;</span></div></body></html>