Swift ARC and Deinitializers
Understand when the last strong reference stops keeping a class instance alive.
How it works
Automatic Reference Counting manages many class-instance lifetimes. A deinitializer runs when an instance is deallocated. It is useful for observing or releasing owned resources, but explicit resource scopes are usually easier to reason about than depending on the timing of unrelated object lifetimes.
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 arc-deinitializers.swift in a new learning folder. On Linux/macOS compile with swiftc -swift-version 6 -parse-as-library arc-deinitializers.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 arc-deinitializers.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 Lease {
init() { print("created") }
deinit { print("released") }
}
func ownedScope() {
let lease = Lease()
withExtendedLifetime(lease) { }
}
@main
struct Lesson {
static func main() {
ownedScope()
print("scope finished")
}
}
Expected result
created released scope finished
The helper owns the only strong reference and keeps it alive through the withExtendedLifetime block. The instance is released before the helper finishes. This demonstrates one controlled lifetime rather than guaranteeing when every optimised program will release arbitrary objects.
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.