2017-05-04 62 views
-2

我可以比较没有关联值的关联枚举大小写吗?请检查下面的代码片段如何比较没有关联值的关联枚举

//Declare associated enum 
enum Example 
{ 
    case test(x:Int) 
    case test1(x:String) 
} 

//Creating enum with associated value 
let testWithAssociatedValue = Example.test(x:0) 
if case .test = testWithAssociatedValue { //WorksFine 
} 

//Now having enum with no associated value 
let testWithNoAssociatedValue = Example.test 

Now Why comparing enum that has no associated value like below,gives me compile error?. 
if case .test = testWithNoAssociatedValue { 
} 

回答

1

因为Example.test不是enum的情况。尝试将代码放入游乐场,或者检查type(of: Example.test)。它会给你(Int) -> Example。也就是说,在引擎盖下,Example.test表现得像一个需要Int的函数,并为您提供了一个Example对象。这就是为什么Example.test(x: 10)给你的枚举案例。

“拥有没有关联值的关联枚举”的概念没有意义。这听起来像你想让关联的类型可选,所以你可以说Example.test(x: nil)