# Efficiently Reaping Weak Collections

**URL:** <https://forums.swift.org/t/efficiently-reaping-weak-collections/78205>\
**Category:** Using Swift\
**Tags:** collection, weak\
**Created:** [March 1, 2025, 8:46am UTC](https://forums.swift.org/t/efficiently-reaping-weak-collections/78205 "2025-03-01T08:46:43Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![bdkjones](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bdkjones/32/13872_2.png) [@bdkjones](https://forums.swift.org/u/bdkjones)\
**Post date:** [March 1, 2025, 8:46am UTC](https://forums.swift.org/t/efficiently-reaping-weak-collections/78205/1 "2025-03-01T08:46:44Z")

</div>

## Context:

I have a `ModelController` that keeps a collection of weak references to `ModelObject`s. The controller receives changes from the cloud and, for each one, sees if the change affects a `ModelObject` in the collection. If so, it updates that object’s properties.

The collection is weak because if nothing in the app other than the `ModelController` is using a given `ModelObject`, we obviously don’t care about it and can let it go.

## Code:

This is the basic (abbreviated) setup:

```swift
class ModelController
{
    // ModelObjects each have a UUID, so we key by that:
    private var cache: [UUID: WeakBox]
}

```

```swift
class WeakBox
{
    weak var wrappedValue: ModelObject?
}

```

## Question:

When `wrappedValue` becomes nil inside `WeakBox`, what is the best strategy for removing that WeakBox instance from the `cache` dictionary so it doesn’t linger?

Property observers don’t fire when ARC nils a reference, so `WeakBox` can’t call back up to `ModelController` on `didSet`.

I know discussions about weak collections go back to the dawn of Swift. In this case, the `cache` collection could see low millions of entries, so cleaning up would be significant. For that same reason, I cannot walk the dictionary and test each entry to see if its `wrappedValue` is nil—we’ve essentially reinvented garbage collection at that point.

Anyone have a Tevanianly clever way to do this?

---

<div class="post-metadata">

**Author:** ![odmir](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/odmir/32/4784_2.png) [@odmir](https://forums.swift.org/u/odmir)\
**Post date:** [March 1, 2025, 4:30pm UTC](https://forums.swift.org/t/efficiently-reaping-weak-collections/78205/2 "2025-03-01T16:30:59Z")

</div>

What if you only check if it’s nil once a change arrives from the cloud for that object and remove the WeakBox then? I would also provide a method to check every box so you can choose the most opportune point to do a full check once in a while in case no updates come from the cloud for a long time.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [March 1, 2025, 5:07pm UTC](https://forums.swift.org/t/efficiently-reaping-weak-collections/78205/3 "2025-03-01T17:07:42Z")

</div>

Not that there are _no_ answers to this, but the fact that it doesn’t have an _easy_ answer is why Swift doesn’t have a set of built-in weak collection types already. :-(

---

<div class="post-metadata">

**Author:** ![bdkjones](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bdkjones/32/13872_2.png) [@bdkjones](https://forums.swift.org/u/bdkjones)\
**Post date:** [March 1, 2025, 6:58pm UTC](https://forums.swift.org/t/efficiently-reaping-weak-collections/78205/4 "2025-03-01T18:58:03Z")

</div>

Yea. Having property observers fire when ARC nils the reference would be the cleanest solution, but I gather that isn’t done because the nilling doesn’t happen eagerly—it gets done on the next load of the value.

I was hoping there’s something dangerous but clever I could do. These objects drive the UI, so everything is bound to the main thread and taking a garbage collection break over many, many entries in the collection is sure to cause beachballs.

I suppose I could do it when the app’s occlusion state changes to occluded (it’s a Mac app) and just hope it completes before the user brings the app back on screen.

---

<div class="post-metadata">

**Author:** ![Slava\_Pestov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/slava_pestov/32/30204_2.png) [@Slava\_Pestov](https://forums.swift.org/u/Slava_Pestov)\
**Post date:** [March 1, 2025, 7:00pm UTC](https://forums.swift.org/t/efficiently-reaping-weak-collections/78205/5 "2025-03-01T19:00:55Z")

</div>

> [@bdkjones](#):
>
> I have a `ModelController` that keeps a collection of weak references to `ModelObject`s. The controller receives changes from the cloud and, for each one, sees if the change affects a `ModelObject` in the collection. If so, it updates that object’s properties.
> 
> The collection is weak because if nothing in the app other than the `ModelController` is using a given `ModelObject`, we obviously don’t care about it and can let it go.

Do you really want to let it go immediately once the last reference is dropped, or keep it alive for a while in case it's needed soon after?

---

<div class="post-metadata">

**Author:** ![Slava\_Pestov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/slava_pestov/32/30204_2.png) [@Slava\_Pestov](https://forums.swift.org/u/Slava_Pestov)\
**Post date:** [March 1, 2025, 7:06pm UTC](https://forums.swift.org/t/efficiently-reaping-weak-collections/78205/6 "2025-03-01T19:06:46Z")

</div>

> [@jrose](#):
>
> Not that there are _no_ answers to this, but the fact that it doesn’t have an _easy_ answer is why Swift doesn’t have a set of built-in weak collection types already. :-(

You can implement an "intrusive" weak dictionary where the keys or values are weak references by having each value store its own key, together with a strong reference to a queue. The value's deinit then adds the key to the queue before a value is deallocated. An insertion into the dictionary first processes the queue and removes empty keys.

EDIT: Now that I think about it, that's probably overkill. Since open addressing usually requires a periodic O(n) rehash to clean up tombstones from deleted keys anyway, if you implement the hashtable yourself, you can just treat a nil weak reference as a tombstone entry for the purposes of lookup and insertion, without imposing any requirements on the weak-referenced key or value stored within.

---

<div class="post-metadata">

**Author:** ![bdkjones](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bdkjones/32/13872_2.png) [@bdkjones](https://forums.swift.org/u/bdkjones)\
**Post date:** [March 1, 2025, 8:04pm UTC](https://forums.swift.org/t/efficiently-reaping-weak-collections/78205/7 "2025-03-01T20:04:44Z")

</div>

> The value's deinit then adds the key to the queue before a value is deallocated.

This should get the job done. Each `ModelObject` has a reference to the `ModelController`, so it can call from `deinit` and pass its ID so that `ModelController` can remove that entry from `cache`.

I was hoping for something more encapsulated because `deinit` plus Swift Concurrency is painful. (`ModelController` is not isolated to @MainActor; I can instantiate instances of it on background actors to do background processing such as bulk imports, etc. so the picture is a little more complex than the example here.)

---

<div class="post-metadata">

**Author:** ![kabiroberai](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kabiroberai/32/28072_2.png) [@kabiroberai](https://forums.swift.org/u/kabiroberai)\
**Post date:** [March 1, 2025, 10:25pm UTC](https://forums.swift.org/t/efficiently-reaping-weak-collections/78205/9 "2025-03-01T22:25:17Z")

</div>

While it may be unnecessary in this case (c.f. @Slava_Pestov's suggestion about amortizing cleanup by treating `nil` as a tombstone), it's possible to leverage Objective-C Associated Objects on Apple platforms to implement a general "observer" that triggers when an object is deinitialized. Something like:

```swift
final class DeinitObserver: Sendable {
  private enum Key {}

  let block: @Sendable () -> Void
  private init(_ block: @escaping @Sendable () -> Void) {
    self.block = block
  }
  deinit { block() }

  static func observe(_ object: AnyObject, perform: @escaping @Sendable () -> Void) {
    let observer = DeinitObserver(perform)
    let key = UnsafeRawPointer(bitPattern: UInt(bitPattern: ObjectIdentifier(Key.self)))!
    objc_setAssociatedObject(object, key, observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  }
}

// usage:
DeinitObserver.observe(myValue) {
  // perform cleanup on deinit
}

```

Not sure of the performance impact this would have though so YMMV.
