[swift-evolution] [Manifesto] Ownership

Jonathan Hull jhull at gbis.com
Mon Mar 6 18:21:17 CST 2017

I ran into this exact issue today.  Would something like inout returns help to fix it?

I have a struct called StyledString which gets rid of much of the frustration of dealing with NSAttributedStrings in Swift.  Basically, you make selections on the string and set some property of it like so:

	styled.paragraph(2).words(3…7).bold = true

and then at the end, you ask for an attributed string:

	myLabel.attributedText = styled.attributedString

The language I originally designed this for (almost 20 years ago) had a special type of function (called a selector) which could be in the middle of a chain of calls, but not at the end of it… which avoided the problem you are talking about here.  In Swift, I basically have a note in the documentation saying not to store the selections in a variable… but that is not ideal.  

It would be nice to have a way to say that the return value is not allowed to be stored (only called as part of a chain).  This would allow mutable views without the issue of them breaking value semantics.


> On Feb 27, 2017, at 9:08 AM, John McCall via swift-evolution <swift-evolution at swift.org> wrote:
>> 3: Mutable Views
>> Currently a major pain point of Swift has been exposing “mutable views” into a type in a reasonable way. Apologies for length, but here’s an extended example:
>>   /// Implements a 2D grid (of size fixed upon initialization).
>>   /// **Not** a `Collection` itself but has many *views* into it that *are* `Collection`s.
>>   ///
>>   struct Grid2D<T> {
>>     // typical CoW backing storage
>>     fileprivate var storage: Grid2DStorage<T>
>>     /// Obtain a linear traversal of our grid:
>>     /// - parameter corner: The corner at which we start (e.g. `northWest`)
>>     /// - parameter motion: The order in which we travel (`latitudeThenLongitude` or `longitudeThanLatitude`)
>>     ///
>>     /// - returns: A read-only `Collection` that visits each grid location in `self`, following the requested traversal
>>     func traversal(from corner: Grid2DCorner, following motion: Grid2DMotion) -> Grid2DTraversal<T>
>>   }
>> …wherein `Grid2DTraversal<T>` is, as noted, a "read-only view” into its parent that also adopts `Collection`.
>> What would be nice is to be able to make that `Grid2DTraversal<T>` into a mutable view in a way that’s also *safe*; what I mean is something like:
>>   extension Grid2D {
>>     mutating func mutatingTraversal<T>(from corner: Grid2DCorner, following motion: Grid2DMotion, _ mutator: (inout Grid2DTraversal<T>) -> R) -> R {
>>       var t = self.traversal(from: corner, following: motion)
>>       return mutator(&t)
>>     }
>>   }
>> …with the specific goals of (a) having mutations applied via `Grid2DTraversal` get directly written-through to the underlying storage (w/out pointless copying) but also (b) making `Grid2DTraversal` generally act safely in all other contexts.
>> As it is the “best” way to squeeze this into the type system at this time is arguably:
>> - define Grid2DTraversal:
>>   - to have as a strong reference to the backing storage
>>   - as only having the read-only methods
>> - *also* define MutableGrid2DTraversal:
>>   - to have an unowned reference to the backing storage
>>   - also include the mutating methods
>> …and then just be careful with API design and patterns of use; in particular only provide access to `MutableGrid2DTraversal<T>` values in the context of closures passed into dedicated functions like `mutatingTraversal`, above…and then just be disciplined never to extract those passed-in values.
>> Needless to say this isn’t a very satisfactory state of affairs—it is well into “why am I bothering with all this?” territory—and it’d be *far* nicer if the ownership system would allow for `Grid2DTraversal`:
>> - to adopt `Collection` without restriction
>> - to adopt `MutableCollection` only in certain ownership contexts
>> - to have reasonable control over where those contexts apply 
> It's not sensible to have a type that conditionally conforms to a protocol based on context.  However, the requirements of MutableCollection are all 'mutating', so you can't actually use them unless you have a mutable value.  So the way to fit what you're asking for into the ownership proposal is to make sure that clients of your view type only have a mutable value when the base was mutable, and the easiest way of getting that is to have the view be vended as storage rather than a return value.  If you think about it, a mutable view can't be an independent value anyway, because if code like this could work:
>   var grid = ... // note that this is mutable
>   var view = grid.traversal(from: p, following: m) // should return a mutable view by design, right?
>   view.mutate() // reflected in grid, right?
> then it completely destroys the value-type properties of 'grid', because 'view' should really be an independent value.
> The proposal suggests doing this instead with storage, so that the view is logically a (mutable) component of the grid.  So on the use side:
>   var grid = ...
>   inout view = &grid[traversingFrom: p, following: m]
>   view.mutate()
> and on the declaration side:
>   struct Grid2D<T> {
>     subscript(traversingFrom corner: Grid2DCorner, following motion: Grid2DMotion) -> Grid2DTraversal<T> {
>       read {
>         yield Grid2DTraversal(...)
>       }
>       modify {
>         var traversal = Grid2DTraversal(...)
>         yield &traversal
>         // ensure changes were applied here
>       }
>     }
>   }
> If you feel that the aesthetics of this leave something to be desired, that's a totally reasonable thing to discuss.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170306/76e9b714/attachment.html>

More information about the swift-evolution mailing list