2015-12-03 30 views
4

使用泛型和類型約束有沒有辦法將此enum的前兩種情況合併爲一個?帶有約束的泛型類型的相關值的枚舉例子

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

附錄: 我知道我可以爲整個enum指定一個泛型類型,但只有這兩種類型的需要之一。另外,我覺得它需要符合兩個EquatableComparable,但我不能完全找到的語法來指定...


編輯:(?)原來Comparable包含Equatable,因此,或許我可以這樣做:

enum AllowedValueRange { 

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

    // (rest omitted) 

(也切換與兩個值的單一的,命名爲元組相關聯的值的一對)

回答

3

可以定義

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?)) 
} 
+0

我明白了。我不喜歡這個解決方案的唯一的事情是,我真的不需要'T'在任何其他'case's;我希望我可以僅爲'NumericRange'聲明它,而不是整個'enum'。我想這是我能得到的最好的。 –

+0

也就是說,我希望聲明:enum AllowedValueRange {case NumericRange ((min:T?,max:T?))/ * ... * /}' –

+1

@NicolasMiari:我明白了,但我不認爲這是可能的。 –