user698515
user698515

Reputation: 21

Get enum value by nested variable

If I have an enum like this:

enum Types: String {
    case first = "First"
    case second = "Second"

    var id: Int {
        switch self {
        case .first: return 1
        case .second: return 2
        }
    }
}

Given an Int value of 2, how would I get the Type, i.e. second?

Upvotes: 1

Views: 56

Answers (1)

Under_Koen
Under_Koen

Reputation: 1078

If you make the enum use the CaseIterable extension you could get a array of all values using Types.allCases.

So you could get the element by doing this:

Types.allCases[id - 1]

Upvotes: 2

Related Questions