Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change the Associated values of a enum?

Tags:

I am reading the Swift tour document, and facing a problem. Here is the code:

enum SimpleEnum {     case big(String)     case small(String)     case same(String)      func adjust() {         switch self {         case let .big(name):             name +=  "not"         case let .small(name):             name +=  "not"         case let .same(name):             name +=  "not"         }     } } 

The function adjust() won't work, I wonder if there is a way to change the Associated value of an enum, and how?

like image 705
wj2061 Avatar asked Jul 18 '15 06:07

wj2061


People also ask

Can enum values be changed?

4) Enum constants are implicitly static and final and can not be changed once created.

What are associated values in enum?

In Swift enum, we learned how to define a data type that has a fixed set of related values. However, sometimes we may want to attach additional information to enum values. These additional information attached to enum values are called associated values.

Can enum values be changed in C?

You can change default values of enum elements during declaration (if necessary).

What are associated values?

Associated values are set when you create a new constant or variable based on one of the enumeration's cases, and can be different each time you do so.


1 Answers

Your most immediate problem is that you're attempting to change the value of an immutable variable (declared with let) when you should be declaring it with var. This won't solve this particular problem though since your name variable contains a copy of the associated value, but in general this is something that you need to be aware of.

If you want to solve this, you need to declare the adjust() function as a mutating function and reassign self on a case by case basis to be a new enum value with an associated value composed from the old one and the new one. For example:

enum SimpleEnum{     case big(String)     case small(String)     case same(String)      mutating func adjust() {         switch self{         case let .big(name):             self = .big(name + "not")         case let .small(name):             self = .small(name + "not")         case let .same(name):             self = .same(name + "not")         }     } }  var test = SimpleEnum.big("initial") test.adjust()  switch test { case let .big(name):     print(name) // prints "initialnot" case let .small(name):     print(name) case let .same(name):     print(name) } 
like image 57
Mick MacCallum Avatar answered Sep 22 '22 03:09

Mick MacCallum