Andrii Chernenko
Andrii Chernenko

Reputation: 10194

Reference Swift enum member without its associated value

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?

Upvotes: 7

Views: 3457

Answers (3)

Long Pham
Long Pham

Reputation: 7582

Try it.

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

Upvotes: -1

Duncan C
Duncan C

Reputation: 131408

You are creating a new instance of the enum. You're error enum has a required associated value. It can't be nil. Thus when you create an enum, you must give it a value.

How about if you make your error state's associated value optional?

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

Then you could use code like this:

let thisDoesnt = state == .Error(nil)

Upvotes: 0

Matteo Piombo
Matteo Piombo

Reputation: 6726

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:

Swift 2.0

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

Hope this helps

Upvotes: 5

Related Questions