I have the following enum:
enum State: Equatable {
case Loading
case Finished
case Error(message: String)
}
func ==(lhs: State, rhs: State) -> Bool {
//...
}
I want to be able to compare enum members. I have overloaded ==
operator, and it works, but there's 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 don't see why I should not be able to reference the enum member 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 actually possible with switch
, so I don't know why regular statements are limited.
I have to admit that I haven't looked at Swift 2 closely. Should I expect some improvements in the new version? Another question is, until it is released, is there any workaround?
In Swift enum, we learned how to define a data type that has a fixed set of related values. However, sometimes we may want to attach additional information to enum values. These additional information attached to enum values are called associated values.
A Swift enum can either have raw values or associated values. Why is that? It's because of the definition of a raw value: A raw value is something that uniquely identifies a value of a particular type. “Uniquely” means that you don't lose any information by using the raw value instead of the original value.
Yes. Any is implicitly strong. If you pass a reference type, it will be a strong reference. It's not quite a "cycle" since nothing "retains" an enum, but as long as the value exists (or any copy of the value), it will hold onto Entity and prevent it from being deallocated.
However, the key word here is “useful”, which means you need to provide an example that is even vaguely real world. For instance, you might describe a weather enum that lists sunny, windy, and rainy as cases, but has an associated value for cloudy so that you can store the cloud coverage.
Enums work really well 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 probably you will appreciate:
if case .Error(message: _) = state {
print("An Error")
}
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With