[Pitch] MutableSpan

Taking your example:

var mutStr = "foo"
mutStr.unicodeScalars.first         // "f"
mutStr.unicodeScalars.append("t")   // ✅ OK - because the string is a 'var'
print(mutStr) // "foot"

This is enabled by the uniquely value-type ability to "put back" unicodeScalars into mutStr through a setter.

var mutStr = "foo"
var scalars = mutStr.unicodeScalars
scalars.append("t")
mut.unicodeScalars = scalars

Without a setter, you don't have value semantics. If a get-only property allows you to modify the state of the original object, it means you have reference semantics.

You cannot have a setter for Span.

var array = [1, 2, 3]
var span = array.span
span[1] = 3 // does this change `array` in your ideal Span implementation?
array.span = span // this is impossible, `array` is inaccessible until `span` is dead
var contiguous: ContiguousArray = [3, 4, 5]
contiguous.span = span // does this work? could this work?

Aside from it being impossible to have a setter for Span, value types can move between mutable and immutable:

let array = [1, 2, 3]
var span = array.span // cannot work, but prevented by what mechanism?
let span = array.span // OK in your ideal Span implementation
var span2 = consume span // what prevents this?

If these things sound like technicalities, you can try to implement Span at home. I ran into these issues trying to implement a value-like Span a while back. Maybe you can do better than me?

3 Likes