Maybe someone can explain to me how does the following work:
% xcrun swift repl
1> struct S { var x: Int }
2> var a = [S(x:1), S(x:2)]
a: [S] = 2 values {
[0] = {
x = 1
}
[1] = {
x = 2
}
}
3> a[1] = S(x:5)
4> print(a)
[__lldb_expr_1.S(x: 1), __lldb_expr_1.S(x: 5)]
5> a[0].x = 3
6> print(a)
[__lldb_expr_1.S(x: 3), __lldb_expr_1.S(x: 5)]
I get line 3 but line 5, not so much. a[0] is a get so we get a copy of the stored value (is that assumption wrong?). Did we somehow get a reference to a non-reference type S?
The Swift standard library copy-on-write collections are built on read and modify as an optimization to defend against "accidental quadratics". See this @Ben_Cohen lecture for more background on that.