[swift-evolution] Allowing mutable members in structs

Joe Groff jgroff at apple.com
Fri Mar 11 11:25:15 CST 2016


> On Mar 11, 2016, at 2:38 AM, Dan Raviv via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Would it make sense to allow mutable properties in structs, which could be mutated even by non-mutating methods?
> 
> I've noticed this could be useful when implementing a non-mutating protocol method. The method semantically doesn't change the state of the protocol's implementor, and therefore shouldn't be declared as mutating. However, *some* implementations might need to change some internal state for implementing the functionality. Making specific struct properties mutable for such a case could make sense.
> 
> Alternatively, Swift could allow implementing a non-mutating protocol method as a mutating method in the implementor. Currently, this doesn't seem to be  allowed; Swift doesn't recognize the mutating method as a match for the non-mutating protocol method.

We currently have the property that, even in generic code, we can assume that an immutable value of type T is safe from read-read races, either because all types are never changed by immutable operations or are accessed through runtime calls with the appropriate synchronization (retain/release, weak references). To preserve these 'let' semantics with mutable fields, it would have to be the implementor's responsibility to ensure its mutating accesses are properly synchronized. Note that you can already get the effect of a mutable field in a struct by embedding a reference to a mutable class reference:

struct Foo {
  var x: Int
  class MutableFields {
    var y: Int
    init(y: Int) { self.y = y }
  }

  private var mutableFields: MutableFields
  var y: Int {
    get { return mutableFields.y }
    set { mutableFields.y = newValue }
  }
}

This can for instance be used to implement a memoized lazy field, as in https://github.com/robrix/Memo.

-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160311/bade3349/attachment.html>


More information about the swift-evolution mailing list