Can I change the associated enumeration values?

I am reading a Swift tour document and am 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 adjust() function will not work, I wonder if there is a way to change the Associated enumeration value and how?

+8
enums swift
source share
1 answer

The biggest problem is that you are trying to change the value of an immutable variable (declared with let ) when you must declare it with var . This will not solve this problem, but since your variable name contains a copy of the associated value, but overall this is what you need to know about.

If you want to solve this problem, you need to declare the adjust() function as a mutation function and reassign yourself in each case to be a new enumeration value with an associated value made up of the old and 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) } 
+19
source share

All Articles