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
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to