How do I avoid retain cycles and memory leaks in Swift?

In Swift, avoiding retain cycles and memory leaks is crucial for efficient memory management. Retain cycles occur when two or more objects hold strong references to each other, preventing them from being deallocated. To prevent this, you can use weak or unowned references.

Here’s a simple example demonstrating how to use a weak reference to avoid a retain cycle in a closure:

class Person { var name: String var apartment: Apartment? init(name: String) { self.name = name } } class Apartment { var unit: String weak var tenant: Person? init(unit: String) { self.unit = unit } } var john: Person? = Person(name: "John") var unit4A: Apartment? = Apartment(unit: "4A") john?.apartment = unit4A unit4A?.tenant = john john = nil // John can now be deallocated, reversing the retain cycle unit4A = nil // Apartment can also be deallocated

Swift retain cycles memory leaks weak reference unowned reference memory management