Enum case with bound value of generic type with constraints

Is there a way, using generalizations and type restrictions, to collapse the first two cases of this enuminto one?

enum AllowedValueRange {

    // Associated value represents (min, max). 'nil' represents
    // "no limit" for that interval end (+/- infinity)
    case IntegerRange(Int?, Int?)


    // Associated value represents (min, max). 'nil' represents
    // "no limit" for that interval end (+/- infinity)
    case FloatRange(Float?, Float?)


    // A finite set of specific values of any type
    case ArbitrarySet([Any])

    // (...Other cases with different structure of associated values
    // or no associated values...)
}

Addendum: I know that I can specify a common type for everything enum, but only these two types are needed. Also, I think it should match both Equatable, and so Comparable, but I cannot find the syntax to indicate that ...


EDIT: Turns out it Comparablecontains Equatable(?), So maybe I can do this:

enum AllowedValueRange {

    // Associated value represents (min, max). 'nil' represents
    // "no limit" for that interval end (+/- infinity)
    case NumericRange((min:Comparable?, max:Comparable?))

    // (rest omitted)

(Also, a pair of related values ​​has been changed with one named tuple of two values)

+4
source share
1 answer

enum AllowedValueRange {
    case NumericRange((min:Comparable?, max:Comparable?))
}

,

let range = AllowedValueRange.NumericRange((min: 12, max: "foo"))

, , , . ( ):

enum AllowedValueRange<T: Comparable> {
    case NumericRange((min:T?, max:T?))
}
+3

Source: https://habr.com/ru/post/1618380/


All Articles