Leem.fin
Leem.fin

Reputation: 42592

Dynamic value for variable stored in enum

I have a enum:

enum Role {
    static let Employee = “employee”
    static let Manager = // it depends on other variable values
}

As you see above, the Manager role value is depending on other values, how to make it so that I can pass parameters to Role for Manager to create the right value for Manager?

(If it is impossible to do with enum, what could be the alternative way?)

Upvotes: 0

Views: 2033

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

You can assign another variable's value to a variable inside an enum just as you would with a class or struct.

let managerName = "manager"

enum Role {
    static let Employee = "employee"
    static let Manager = managerName
}

print(Role.Manager) //prints manager

The only thing you cannot assign dynamically is the RawValue of a case of the enum. RawValues have to be literals.

enum Role:String {
    static let Employee = "employee"
    static let Manager = managerName
    case employee, manager = managerName //error: Raw value for enum case must be literal
}

Upvotes: 3

Related Questions