I was building a collection object recently, which stores an array of tuples: 
(Range<I>, T) - some generic type, and a range. 
Part of the workings of the collection involves splitting these tuples, which 
means we need to split the Range (easy enough) and duplicate T.

In practice, I was using value types for T (it was another Array), so I could 
duplicate by assignment; but what if somebody stuck an NSArray or other 
reference-type in instead?

My first thought was - I could allow it, create some “Copyable” protocol and 
require conformance. But there are other guarantees I get from value types as 
well. Let’s say I had a sorted Array of T; if T could be a reference-type, 
anybody who gets a T from the collection could mutate it and invalidate the 
sort order at any time! That could lead to unexpected behaviour, such as 
infinite loops in binary-search algorithms, and it might not be obvious to a 
user of the collection how that happened (or that it’s even their fault - how 
are they supposed to know this is kept in a sorted Array, especially if it’s 
wrapped by another type, and that this particular search algorithm could 
infinitely loop if the Array is not sorted?). I could return a copy from the 
getter, but at this point I’m basically re-inventing value-type semantics for 
classes while creating burdensome requirements for actual value-types.

Actually, this is a problem with the language in general. While we have a way 
to specify that a generic type or protocol must obey reference-type semantics 
(via “<T where T:AnyObject>”, “protocol MyProtocol : class”), we don’t have a 
value-type semantic counterpart.

So I’d like to see us provide an “AnyValue” and “value” equivalent. We should 
be able to require that generic types or protocols are satisfied by values so 
we know how to treat them.
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to