How do I prevent retain cycles with closures and delegates in Swift?

In Swift, retain cycles can occur when you use closures and delegates, leading to memory leaks because objects reference each other. To prevent this, you can use weak or unowned references within your closures or delegate implementations.

class MyClass { var completion: (() -> Void)? func start() { // Using [weak self] to prevent retain cycles completion = { [weak self] in guard let self = self else { return } self.doSomething() } } func doSomething() { print("Doing something") } } class AnotherClass { var myClassInstance: MyClass? func test() { myClassInstance = MyClass() myClassInstance?.start() myClassInstance?.completion?() } }

Prevent retain cycles Swift closures Swift delegates Memory management Weak references Unowned references