Link Swift enum member without an associated value

I have the following listing:

enum State: Equatable { case Loading case Finished case Error(message: String) } func ==(lhs: State, rhs: State) -> Bool { //... } 

I want to be able to compare enumeration members. I overloaded the == operator and it works, but there is a problem:

 let state: State = .Loading // works just fine let thisWorks = state == .Finished // this does as well let thisWorks2 = state == .Error("Derp!") // this, however, does not, compiler error: "Could not find member 'Error'" let thisDoesnt = state == .Error 

This seems to be a compiler limitation. I do not understand why I cannot refer to an enumeration element without its associated value. Apparently, I don't care about the error message associated with .Error , I just need to know if an error has occurred. This is possible with switch , so I don't know why regular statements are limited.

I must admit that I did not look very closely at Swift 2. Should I expect some improvements in the new version? Another question, until it is released, is there a workaround?

+6
source share
3 answers

Enums work fine with switch :

 let state: State = .Error(message: "Foo") switch state { case .Loading: print("Loading") case .Finished: print("Finished") case .Error(message: "Foo"): print("Foo!!!") case .Error(message: _): print("Some other error") } 

Swift 2.0 will bring another control flow syntax that you will probably appreciate:

Swift 2.0

 if case .Error(message: _) = state { print("An Error") } 

Hope this helps

+4
source

A new enumeration instance is created. Your enum error has the necessary meaning. It can be nothing. Thus, when creating an enumeration, you must give it a value.

How about if you added an optional error status state?

 enum State: Equatable { case Loading case Finished case Error(message: String?) 

Then you can use this code:

 let thisDoesnt = state == .Error(nil) 
+2
source

Give it a try.

 let thisWorks2 = state == .Error(message: "Derp!"); 
-1
source

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


All Articles