ARC and Weak References
Lesson 29 of 48 in Coddy's Swift for Dart Developers course.
Dart uses tracing garbage collection, which can reclaim unreachable cycles of ordinary objects. Reclamation timing is not a deterministic cleanup contract. Swift ARC tracks strong references to class instances; a cycle of strong references can keep objects alive after outside references disappear. A weak reference does not keep its referent alive and becomes nil after deallocation, so it must be optional and mutable. An unowned reference also does not retain, but assumes its referent is still alive when accessed; violating that assumption is a runtime error. Neither is a general performance promise. This example breaks a parent-child back edge while the objects are still alive, without relying on garbage-collection timing.
Complete Dart program. Each labelled block is a separate file.
Node.dart
class Node {
final String name;
Node? parent;
Node(this.name);
}main.dart
import 'Node.dart';
void main() {
final parent = Node('root');
final child = Node('leaf');
child.parent = parent;
print(child.parent?.name ?? 'none');
child.parent = null;
print(child.parent?.name ?? 'none');
}Complete Swift program. Each labelled block is a separate file.
Node.swift
import Foundation
final class Node {
let name: String
weak var parent: Node?
init(_ name: String) { self.name = name }
}main.swift
import Foundation
let parent = Node("root")
let child = Node("leaf")
child.parent = parent
print(child.parent?.name ?? "none")
child.parent = nil
print(child.parent?.name ?? "none")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 Dart 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