I want to capture a reference to self
, and I am having some difficulty.
Here’s an example:
struct Reference<T> {
var getter: ()->T
var value: T { return getter() }
init(_ value: @escaping @autoclosure ()->T) {
getter = value
}
}
This type captures a reference to the value it is initialized with:
var a = [0]
let r = Reference(a)
a = [1, 2, 3]
print(r.value) // [1, 2, 3]
The reference r
sees the new, updated value of a
, and it does not trigger copy-on-write. This is exactly what I want.
However, if we make a convenience member on Array
for creating such a reference, it behaves differently:
extension Array {
var reference: Reference<Array> {
return Reference(self)
}
}
var b = [0]
let s = b.reference
b = [1, 2, 3]
print(s.value) // [0]
This time, the reference does trigger copy-on-write, and it does not see the new, updated value of b
. This is not what I want.
Is there any way to make this work, so that I can write a.reference
instead of Reference(a)
and have it do the same thing?
(The difference in spelling may seem trivial, but it becomes important when conforming to protocols.)