Swift Weak References and Capture Lists
Break an ownership cycle without promising the referenced object will always exist.
How it works
A weak reference does not keep an instance alive and becomes nil after deallocation. Weak references are optional. Capture lists can express weak ownership in closures. Use unowned only when the lifetime relationship is genuinely guaranteed; it is not a convenient way to avoid handling nil.
Run this Swift example
Install the toolchain for your platform from Swift.org, then check swift --version. The reviewed portable baseline is Swift 6.4.2 in Swift 6 mode on Ubuntu 26.04 x86_64 through the PC’s existing WSL installation. These are real Linux executions, not claims of Windows-native or Apple-platform test results. Windows Swift has separate C++/SDK prerequisites in its official setup guide.
Save the complete source as weak-references-capture-lists.swift in a new learning folder. On Linux/macOS compile with swiftc -swift-version 6 -parse-as-library weak-references-capture-lists.swift -o lesson, then run ./lesson. On a configured Windows toolchain use an output such as lesson.exe and run .\lesson.exe. The parse-as-library option supports the explicit @main entry point used by these sources. Compile each ordinary lesson separately.
Bhylu has no Swift browser runner. The JavaScript/Python editors do not run these sources; Apache, PHP and MySQL are not required. Downloads are source text, never executable teaching endpoints.
Download the complete weak-references-capture-lists.swift · Download all source files with hash checks
For the optional collection, save download-examples.mjs in a new folder and run node download-examples.mjs. A local preview uses node download-examples.mjs http://127.0.0.1:8000/examples/swift/. It refuses an existing bhylu-swift-examples folder and installs or executes no Swift automatically. Apple-only files remain separate Xcode learning examples, not a portable Swift package target.
Example
final class Owner { var child: Child? }
final class Child { weak var owner: Owner? }
@main
struct Lesson {
static func main() {
let child = Child()
do {
let owner = Owner()
owner.child = child
child.owner = owner
print(child.owner != nil)
}
print(child.owner == nil)
}
}
Expected result
true true
Owner strongly owns the child while the child refers weakly back to the owner. When the local owner leaves scope, the remaining child reference does not keep it alive. A closure stored by its captured owner can require the same ownership review.
Primary references: The Swift Programming Language and Apple framework documentation. Use the selected platform’s current requirements. Fictional workshop examples do not establish production safety or deployment approval.