These patterns help avoid memory problems when objects refer to each other. They keep your app running smoothly without crashes.
0
0
Weak self and unowned self patterns in Swift
Introduction
When you have two objects that refer to each other and want to avoid memory leaks.
When using closures that capture self inside a class to prevent strong reference cycles.
When you want to safely access self inside a closure without keeping it alive forever.
When you know self will always exist while the closure runs and want to avoid optional unwrapping.
When you want to prevent your app from crashing due to unexpected nil values in closures.
Syntax
Swift
someClosure = { [weak self] in
guard let self = self else { return }
// use self safely here
}
someClosure = { [unowned self] in
// use self directly here
}weak self creates a temporary, optional reference to self that can become nil.
unowned self creates a non-optional reference but assumes self will never be nil.
Examples
This example uses
weak self to avoid a strong reference cycle. It safely unwraps self before use.Swift
class Example { var closure: (() -> Void)? func setup() { closure = { [weak self] in guard let self = self else { return } print("Using weak self safely") } } }
This example uses
unowned self assuming self will always exist when the closure runs.Swift
class Example { var closure: (() -> Void)? func setup() { closure = { [unowned self] in print("Using unowned self directly") } } }
Sample Program
This program shows how weak self safely handles the case when the object is gone, while unowned self assumes the object is still there.
Swift
class Person { let name: String var greeting: (() -> Void)? init(name: String) { self.name = name } func greetWeak() { greeting = { [weak self] in guard let self = self else { print("Person no longer exists") return } print("Hello, my name is \(self.name) using weak self") } } func greetUnowned() { greeting = { [unowned self] in print("Hello, my name is \(self.name) using unowned self") } } } var person: Person? = Person(name: "Alice") person?.greetWeak() person?.greeting?() person = nil var person2: Person? = Person(name: "Bob") person2?.greetUnowned() person2?.greeting?() person2 = nil
OutputSuccess
Important Notes
Use weak self when self might become nil and you want to avoid crashes.
Use unowned self only when you are sure self will not be nil during closure execution.
Always test your code to avoid unexpected nil errors or memory leaks.
Summary
Weak self helps avoid memory leaks by allowing self to become nil inside closures.
Unowned self assumes self will always exist and avoids optional unwrapping.
Choosing the right pattern keeps your app safe and efficient.