[swift-evolution] Class mutation model and value-constrained protocols
david at alkaline-solutions.com
Tue Jul 5 17:19:20 CDT 2016
> If we are going to maintain source stability after Swift 3, it seems
> that we either need to address this now, or decide that it won't be
> addressed, because of the “viral const” problem.
IMHO immutable instances and value vs reference allocation are separate concerns. Just like you can have a struct which contains a memory reference or class that provide shared state, you can a class which is immutable and only represent changes via new object instances.
However, mutable methods and property setters do not expose the ability for a class to behave in this manner, as they have an effective inout self which is not exposed to code. There are optimizations which couldn’t be taken with this sort of approach, but it would certainly be valid for a class to implement “value semantics” with language support. There are abstractions available when using classes that are not available using structs/enums, including class clusters and the State pattern with open subclassing.
If it is impossible for a class to implement the requirements of say MutableCollection, then it makes sense to limit it to value types. But I’ll claim thats a limitation of the language’s support for letting people implement said protocols with immutable reference types, one that we might one day wish to allow for.
All that said, even if a class cannot implement MutableCollection today, they still would be in violation of the protocol with no changes - they just wouldn’t get compiler errors as a result. So given the other enthusiastic proposals in flight, I’d consider such compiler errors to be additive.
> One idea that Jordan and I have floated is that protocols with mutating
> methods should be constrained to applying to non-class types. That
> would be a step in the right direction, but, that still leaves cases
> like gg able to easily violate expectations when the protocol in
> question has no mutating methods.
> Another possibility would be to formalize the idea of value semantics in
> protocol declarations, so that non-class protocols were only allowed to
> apply to values.
> It's also possible that I've overestimated the seriousness of the issue
> and we actually can afford to postpone thinking about it until after
> Swift 4.
> swift-evolution mailing list
> swift-evolution at swift.org
More information about the swift-evolution