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

Brent Royal-Gordon brent at architechies.com
Thu Dec 17 08:42:28 CST 2015

> 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
	    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

More information about the swift-evolution mailing list