swift - Can I change the Associated values of a enum? -
i reading swift tour document, , facing problem. here 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, wonder if there way change associated value of enum, , how?
your immediate problem you're attempting change value of immutable variable (declared let
) when should declaring var
. won't solve particular problem though since name
variable contains copy of associated value, in general need aware of.
if want solve this, need declare adjust()
function mutating function , reassign self on case case basis new enum value associated value composed old 1 , new one. 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) }
Comments
Post a Comment