[swift-evolution] References in Value Types (Deep-Copy-OnWrite)

Andrew Bennett cacoyi at gmail.com
Thu Dec 17 09:50:30 CST 2015


I agree with pretty much everything you said, although I'm not saying we
should "solve" this, but that we should discuss it. One thing we might be
able to do is instead of trusting the person writing the type to:

   - "provide the expected semantics, or to document any deviations"

we may trust the person writing the type to:

   - "annotate the type with the expected semantics"

If such annotations existed. It wouldn't force everything to be c-like, but
it could allow them to be predictable.

I'm not saying annotations are the way to go, just that there is an issue,
you seem to agree, and that it'd be nice to brainstorm it.



On Fri, Dec 18, 2015 at 1:42 AM, Brent Royal-Gordon <brent at architechies.com>
wrote:

> > TL;DR: You can make a struct look like a class, a class look like a
> struct, a mutable type appear immutable.
>
> This is simply not possible to prevent, at least without turning structs
> into dumb data structures a la C. Here’s something that’s value types all
> the way down, but behaves like a reference type:
>
>         struct MyValue {
>             private static var realValues: [Int] = []
>             private let index: Int
>
>             init(value: Int) {
>                 self.index = MyValue.realValues.count
>                 MyValue.realValues.append(value)
>             }
>             var value: Int {
>                 get { return MyValue.realValues[index] }
>                 set { MyValue.realValues[index] = newValue }
>             }
>         }
>
> Similarly, you can make reference types with value-like semantics—think of
> NSDate, which is a reference type, but is immutable and only provides
> operations which return a new instance. The ultimate proof of this is not
> in Swift but in Ruby, where even simple numbers are objects, but they offer
> no mutation operations so they behave just like value-typed numbers in
> other languages.
>
> Ultimately, you just have to trust the person writing the type to provide
> the expected semantics, or to document any deviations. (GeneratorType,
> which does not require even struct-based generators to guarantee that they
> will iterate separately if you copy them, are an example of the latter.)
> This leaves room for mischief, but that’s life in a Turing machine.
>
> --
> Brent Royal-Gordon
> Architechies
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151218/b2110870/attachment-0001.html>


More information about the swift-evolution mailing list