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?
4) Enum constants are implicitly static and final and can not be changed once created.
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.
You can change default values of enum elements during declaration (if necessary).
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.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With