Luke
Luke

Reputation: 9690

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()
        }
    }

}

Upvotes: 1

Views: 1326

Answers (1)

tktsubota
tktsubota

Reputation: 9391

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()
        }
    }

}

Upvotes: 1

Related Questions