Reference-type easily have reference cycle because we allow it to have multiple points of access(POA). For example,
let a = Class() // Class #1
let b = a // also Class #1
So we say that Class 1 has 2 POAs; a
and b
.
Semantically, value-type always have only one POA. For example,
let a = Value() // Value #1
let b = a // treated as Value #2
So Value 1 has only one POA, a
. And Value 2 has only b
. That’s why weak
reference makes no sence for value type; it’ll turn nil
The moment it is assigned.
The problem with closure is that it allows any variable to have multiple POAs regardless of value/reference semantic.
let a = Value() // Value #1
let c = {
use(a) // also Value #1
}
Now Value #1 has 2 POAs one in the local context, and another inside the closure.
Despite both being called a
, it should be treated as a different POA as it lies in different scopes, and so Value #1 will be inaccessible only when both scopes expire.
So I think the short-term way of addressing this would be to allow closure to weakly capture the value type.
let a = Value()
let c = { [weak a]
use(a)
}
Though if we’re revamping the Memory model anyway, effort/pay-off may not be very attractive.