There are no weak collections in the standard library (hopefully just yet).
You might want to try implementing such set yourself by wrapping the standard one by declaring a weak box like that:
struct WeakBox<T: AnyObject & Hashable> {
weak var item: T?
func hash(into hasher: inout Hasher) {
hasher.combine(item)
}
}
and use a Set<WeakBox<UIView>>
.
The issue is that these boxes stay in the set even when the boxed object becomes deallocated. This might not seem like a huge problem at first, but this violates the fundamental property of sets: they normally promise to be a collection of unique elements. Let's see what happens if you naively use this implementation:
var set = Set<WeakBox<MyClass>>()
var mc1: MyClass? = MyClass()
var mc2: MyClass? = MyClass()
set.insert(WeakBox(item: mc1))
set.insert(WeakBox(item: mc2))
print(set.count) // prints "2" — so far, the elements are unique
mc1 = nil
mc2 = nil
print(set.count) // prints "2" — two non-unique elements!
I believe that's one of the reasons why the standard library doesn't provide an obvious solution yet. So, you should be careful using weak sets and maybe try finding a different solution for your case.