← frouo.com


Swift 5

How to declare an array of weak references in Swift

let foo = Foo()

var foos = [() -> Foo?]()
foos.append({ [weak foo] in return foo })

// Usage:
foos.forEach { $0()?.doSomething() }

That's it 🎉

No extra struct or class needed.

How does it work?

[weak foo] is the trick. Instead of storing a strong reference of foo, we store a function that captured foo as weak.

FP?

Yes, it is a functional programming approach.

Indeed, we did not create any class or a struct to achieve this. We simple declared a function let captureWeakFoo: () -> Foo? = { [weak foo] in return foo }.

Don't be afraid with () -> Foo?. Tell yourself that it is just a type! It is. It's the type defining a function that takes no parameter and returns an optional Foo.

Do not hesitate to create a typealias if it comes more readable for you

typealias WeakArray<T> = [() -> T?]

Thank you

Hope it helps. Please drop a ❤️ on my Twitter post to show your support 🙏.

The source code for this blog is available on GitHub.