lukech lukech - 4 months ago 7
Swift Question

Associating a type with a Swift enum case?

I’m using Swift 2, and I’d like to associate a

struct
type with each case in an
enum
.

At the moment, I’ve solved this by adding a function to the enum called
type
which returns an instance of the relevant type for each case using a switch statement, but I’m wondering if this is necessary. I know you can associate strings, integers etc. with a Swift enum, but is it possible to associate a type, too? All structs of that type conform to the same protocol, if that helps.

This is what I’m doing now, but I’d love to do away with this function:

public enum Thingy {

case FirstThingy
case SecondThingy

func type() -> ThingyType {
switch self {
case .FirstThingy:
return FirstType()
case .SecondThingy:
return SecondType()
}
}

}

Answer

I think you are saying that you want the raw value to be of type ThingyType, but that is not possible.

What you could do is make type a computed property, to remove the () and only needing to access it with thingy.type.

public enum Thingy {

    case FirstThingy
    case SecondThingy

    var type: ThingyType {
        switch self {
        case .FirstThingy:
            return FirstType()
        case .SecondThingy:
            return SecondType()
        }
    }

}