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)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…