ARC and Weak References
Lesson 29 of 48 in Coddy's Swift for C++ Developers course.
C++ RAII ties resource cleanup to object destruction, so this automatic Lease destructor runs when its block ends, including ordinary exception unwinding. Swift ARC manages class references and can be prevented from releasing objects by strong cycles. The target uses an explicit close operation with defer to guarantee cleanup at the function boundary instead of relying on an assumed ARC release instant. C++ shared_ptr and weak_ptr provide optional shared ownership facilities; raw pointers do not become self-zeroing observers. Swift weak references become nil without retaining the instance, while unowned assumes a valid lifetime. Resource cleanup and heap-memory management are related but separate contracts.
C++
Complete program file: main.cpp.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
struct Lease { ~Lease() { std::cout << "closed\n"; } };
int main() {
{ Lease lease; std::cout << "work\n"; }
}
Swift
Complete program file: Lease.swift.
final class Lease { func close() { print("closed") } }Complete program file: Functions.swift.
func performWork() {
let lease = Lease()
defer { lease.close() }
print("work")
}Complete program file: main.swift.
performWork()Challenge
EasyImplement Member with immutable name: String and init(name:). Implement Membership with weak optional member: Member? and init(member:). The membership must not keep the member alive. Input is one ASCII name of 1 through 20 letters. Create a member in an optional owner, create a membership, print its member name, clear the sole owner, and report whether the membership is now nil as name true.
Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.
Your code goes in Member.swift, Membership.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.
Try it yourself
import Foundation
func apiChecks(_ input: String) -> Bool {
var owner: Member? = Member(name: "Heldout"); let link = Membership(member: owner!); guard link.member === owner else { return false }; owner = nil; return link.member == nil
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for C++ Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules3Control Flow
Switch and PatternsEnums as Finite ChoicesFor Loops and RangesWhile and Repeat LoopsRecap: Sequence Scan6Values and References
Structs and Independent CopiesStored and Computed PropertiesClasses and Shared IdentityARC and Weak ReferencesRecap: Value BasketPractice on your own: Swift playground