What is the use of 'weak' keyword in Swift?
Instruction: Explain the significance of the 'weak' keyword and how it is used in Swift development.
Updated
Official answer
A Swift weak reference observes a class instance without owning it. It does not keep the target alive and is automatically set to nil when that target is deallocated. A weak stored reference must therefore be a variable with an optional class type or a class-bound protocol type.
This standalone example models a non-owning delegate. The separate owner variable keeps the delegate alive until it is cleared:
protocol CompletionDelegate: AnyObject {
func completed()
}
final class Controller: CompletionDelegate {
private(set) var count = 0
func completed() { count += 1 }
}
final class Worker {
weak var delegate: (any CompletionDelegate)?
func finish() { delegate?.completed() }
}
let worker = Worker()
var owner: Controller? = Controller()
worker.delegate = owner
worker.finish()
assert(owner?.count == 1)
owner = nil
assert(worker.delegate == nil)
worker.finish() // Safe: there is no longer a delegate.
Choose the ownership relationship first. A weak delegate is useful when another component owns it; assigning a newly created object only to a weak property can let it disappear immediately. Likewise, [weak self] in a stored closure can break a cycle, but the closure must handle self being absent. Weak references do not make shared mutable state thread-safe.