[swift-users] Restricting associated values

Nevin Brackett-Rozinsky nevin.brackettrozinsky at gmail.com
Sun Jun 18 21:30:53 CDT 2017


Is there a way to restrict the associated values of an enum? For example,
suppose I have this type:

enum Angle {
    case radians(Double)
    case degrees(Double)
}

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).

I don’t see a way to do it. Is this possible?

The closest I’ve found is to create auxiliary types such as

struct Degree { … }
struct Radian { … }

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.

Is there a better way?

Nevin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170618/69c06865/attachment.html>


More information about the swift-users mailing list