Prakash Raman
Prakash Raman

Reputation: 13923

Update / change the rawValue of a enum in Swift

Taking the below enum for instance

enum Name : String {

  case Me = "Prakash"
  case You = "Raman"

}

Can I do the following

Change the raw value of one "case" to something else.

Name.Me = "Prak"

Add a new case to the ENUM

Name.Last = "Benjamin"

Thanks!

Upvotes: 10

Views: 7646

Answers (2)

Pradeep K
Pradeep K

Reputation: 3661

No you cannot. Instead You can redefine your enum to contain associated values instead of raw values.

enum Name {
    case Me(String)
    case You(String)
    case Last(String)
}

var me = Name.Me("Prakash")
print(me)
me = .You("Raman")
print(me)
me = .Last("Singh")
print(me)

Upvotes: 7

vadian
vadian

Reputation: 285039

Short answer: No, you can't.

Enumeration types are evaluated at compile time.
It's not possible to change raw values nor to add cases at runtime.

The only dynamic behavior is using associated values.

Reference: Swift Language Guide: Enumerations

Upvotes: 9

Related Questions