4 ms·
Values can't be mutated if they're Ivars and you're in a non-mutating func. Non-mutating funcs are unique to value semantics.
by drewcrawford 11y ago
Values can't be mutated if they're Ivars and you're in a non-mutating func. Non-mutating funcs are unique to value semantics.
- mikeash 11y agoTrue but I'm not sure what your point is. If you need a mutating struct method then of course you have to mark it as mutating.
- yawaramin 11y agoThe point is that you don't always want to mark the method as mutating. This is explained in the article.
- mikeash 11y agoThis is described in the article. I wouldn't say that it's explained. It makes no sense to me. Whether a method mutates state should be evident when you make it. The very concept of a value-type method which mutates state but isn't marked as mutating makes no sense at all. It sounds like it might be a case where you actually wanted reference semantics but accidentally used value semantics and are trying to make it work anyway.
- drewcrawford 11y agoOne does not "simply" mark a method as mutating. A) One must ensure that one's callers are also mutating, or otherwise have an assignable reference, all the way up the stack B) One must mark the applicable function in the protocol interface as mutating, which may or may not be under your control C) One must now repeat step A for all consumers of the protocol in step B, even if none of the other implementations of that protocol mutate their own state Of course one can design one's architecture specifically with a view toward making ABC trivial, but in the general, unrestricted, default, I-had-other-problems-that-day-and-didn't-think-about-it case, they are hard. That is why I find calls to "just learn value semantics" necessary but insufficient. Value semantics will not refactor my code when I discover-by-surprise that 18 functions need to become mutating, breaking API compatibility across several build targets, because I failed to forsee a necessary mutation 8 months ago.
- mikeash 11y agoI have trouble imagining a scenario like you describe. "All the way up the stack" should be, what, two or three levels at most? And whether or not a particular method is one that changes state or just fetches it should be evident from its semantics. What are you doing where you would suddenly discover that a method is mutating, months after you originally created that method?