# Avoiding unbreakable reference cycle with value types and closures?

**URL:** <https://forums.swift.org/t/avoiding-unbreakable-reference-cycle-with-value-types-and-closures/18757>\
**Category:** Pitches\
**Tags:** ownership, memory-safety\
**Created:** [December 12, 2018, 8:59am UTC](https://forums.swift.org/t/avoiding-unbreakable-reference-cycle-with-value-types-and-closures/18757 "2018-12-12T08:59:17Z")\
**Posts on this page:** 1\
**Showing post:** 20

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [December 18, 2018, 6:15am UTC](https://forums.swift.org/t/avoiding-unbreakable-reference-cycle-with-value-types-and-closures/18757/20 "2018-12-18T06:15:09Z")

</div>

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.

---

_[View the full topic](https://forums.swift.org/t/avoiding-unbreakable-reference-cycle-with-value-types-and-closures/18757)._
