Search code examples
swiftgenericsenumscomparableequatable

Compare enums in Swift


I have a class that contains two enums like so (made simple):

class Errors {
    enum UserError: String {
        case NoToken = "No token!"
        case NoPassword = "No password!"
    }

    enum BackendError: String {
        case NoConnection = "No connection!"
        case ServerBusy = "Server is busy!"
    }
}

Now I want to write generic a function, that accepts either an UserError or an BackendError and return a String depending on the input. Something like this:

func alert(type: /* Accepts Error.UserError or BackendError*/) -> String {
    // checks if UserError or BackendError and returns .rawValue
}

My first approach was to use generics - but frankly, I'm having trouble understanding this concept and I have an inclination I'm fundamentally wrong here. What I did was:

func alert<T>(type: T) {
    if type == Errors.UserError {
        return Errors.UserError.NoPassword.rawValue
    } else {
        return Errors.BackendError.NoConnection.rawValue
    }
 }

Obviously, this does not work.

binary operator cannot be applied to operands of type 'T' and 'Errors.UserError.Type'

I understand this has something to do with the missing implementation Equatable/Comparable protocols and my general lack of understanding of using generics. My questions are:

  1. How can I compare my generic "type" parameter with my enum?

  2. Is my understanding of generics totally wrong?

Also: I would like to avoid the AnyObject approach.


Solution

  • The thing your enums have in common and that you want to take advantage of is that they are RawRepresentable where their RawValue type is String.

    So you need a function like:

    func alert<T: RawRepresentable where T.RawValue == String>(t: T) -> String {
        return t.rawValue
    }