[swift-evolution] Assigning to 'self' in protocol extensions

Russ Bishop xenadu at gmail.com
Sat Jan 21 00:17:28 CST 2017


> On Jan 19, 2017, at 11:11 PM, Slava Pestov via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On Jan 19, 2017, at 10:52 PM, rintaro ishizaki via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>> From the perspective of the caller, I think, this behavior is counterintuitive because we use "reference types" with an expectation: the referencing address would never be changed unless we explicitly replace the object by re-assigning to the variable in call sites, e.g.,
>> 
>> 
> 
> Well, there’s no real difficulty here, other than potential user confusion. The ‘self’ parameter for a mutating method is passed inout, so this behaves as if you called a global function with an inout argument. The difference is of course when you pass a non-self inout argument, the compiler requires you to use the explicit & syntax at the call site.
> 
> Is your proposal to ban calls to such mutating methods on a type that is known to be a reference type at compile time altogether? This will create an inconsistency between code that operates on concrete types and code that operates on generic parameters (in the latter case the compiler of course has no way to statically guarantee that the value is not a reference type).
> 
> The last time this quirk came up in internal discussions, the thought some of us had was that it might be worthwhile to prohibit classes from conforming to protocols with mutating requirements altogether. If you think about it, this makes some amount of sense — it seems like it would be quite hard to write code that can operate on both mutable values and mutable references generically, since the latter do not have value semantics:

Right now you could consider mutable vs non-mutable functions as “advisory” for reference types since it is up to you to fulfill that contract.  

I suppose you could say that reference type members can’t do any stores to self unless the function is decorated in some way to advise the compiler that the mutation is intended but that’s a big change and not terribly useful. It would still be on the programmer to use the special decoration only in appropriate places that obey the mutability invariant (think a LRU cache doing a read() where mutation is not observable by the caller).

The alternate world where I can’t have value and reference types conform to the same protocol if the protocol has any mutating methods is a bit stifling.


IMHO in this case the consistency is more important than the quirk. 


Russ

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170120/2a369fdb/attachment.html>


More information about the swift-evolution mailing list