ARC and Weak References
Lesson 29 of 48 in Coddy's Swift for Java Developers course.
Java garbage collection can reclaim an unreachable cycle; collection timing is not a deterministic resource-release mechanism. Swift ARC manages class instances through strong reference ownership. A cycle of strong references can keep otherwise unused objects alive, so ownership relationships matter.
Weak Swift references do not keep an instance alive and become nil when it is deallocated. They use a mutable optional binding. An unowned reference also does not keep the instance alive, but assumes the instance remains valid for each access; accessing a dangling unowned reference traps. Neither qualifier is a general performance promise.
The examples keep a drawing session alive through a strong alias after clearing its first owner. The Swift observer is weak, yet still sees the session because the keeper is strong. Java WeakReference likewise does not own the referent strongly, but System.gc is only a request and should not be used to assert an exact reclamation instant.
Java: complete program
Session.java
public class Session {
public final String name;
public Session(String name) { this.name = name; }
}Main.java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) throws Exception {
Session owner = new Session("canvas");
Session keeper = owner;
java.lang.ref.WeakReference<Session> observer = new java.lang.ref.WeakReference<>(owner);
owner = null;
System.out.println(observer.get().name);
java.lang.ref.Reference.reachabilityFence(keeper);
}
}Swift: complete program
Session.swift
import Foundation
final class Session {
let name: String
init(name: String) { self.name = name }
}main.swift
import Foundation
var owner: Session? = Session(name: "canvas")
let keeper = owner!
weak var observer: Session? = owner
owner = nil
withExtendedLifetime(keeper) { print(observer?.name ?? "gone") }Use weak when absence is allowed and handle nil. Choose unowned only when the lifetime relationship guarantees validity whenever accessed; do not choose it based on an assumed speed advantage.
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 Java 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