[swift-evolution] [Bug?] Reference types and mutating methods

James Froggatt conductator at ntlworld.com
Sat Apr 30 06:52:22 CDT 2016

I don't believe this has been addressed, please correct me if I'm wrong.

--My Situation--
I've recently been working on an observable collection type. Because each stores ‘subscriptions’ to changes that occur, it made sense to me that this should be a reference type, so subscriptions can't be copied with the values themselves.

I have made this class conform to RangeReplaceableCollectionType, providing it with all the standard collection functions. I do the following:

let array: ObservedArray<String> = []
array.append("1") //Error: Cannot use mutating member on immutable value: ‘array’ is a ‘let’ constant

I have to make the reference immutable just to use my new collection type? This is a bit of a deal-breaker.

--The Problem--
Mutating methods allow ‘self’ to be reassigned, which is just another way to mutate a value type. However, reassigning ‘self’ has a special meaning to reference types, which is presumably the reason they are disallowed in classes.

However, classes can conform to protocols with mutating methods, leading to the compiler disallowing calls to mutating methods for ‘let’ values of type ‘protocol<MutatingProtocol, AnyObject>’, which can be an annoyance in generic code. In addition, classes can inherit mutating methods from protocol extensions, leading to the behaviour I describe above.

Is this intentional behaviour? Am I going about this in the wrong way? Or is this really an omission in the language?

More information about the swift-evolution mailing list