ARC and Weak References
Lesson 29 of 48 in Coddy's Swift for PHP Developers course.
PHP uses reference counting plus cyclic garbage collection. WeakReference observes an object without retaining it, and get returns null once it is gone. This acyclic token has no remaining strong owner when observer returns; a cycle would require considering garbage collection rather than generalizing that timing to every object graph.
Swift class instances use automatic reference counting. Strong references keep an instance alive, while weak references do not and become nil after deallocation. A strong reference cycle can keep objects alive after outside owners disappear. An unowned reference requires a valid lifetime relationship and traps if accessed after its target is gone.
Both observers see a live token during construction and absence afterwards. Swift's weak capture is part of its ownership model, while PHP exposes an observer object. Use weak observation only when the relationship should not extend lifetime, and plan for the observed object being absent.
Complete PHP comparison program:
<?php
declare(strict_types=1);
class Token {}
function observer(): WeakReference {
$token = new Token();
$view = WeakReference::create($token);
echo $view->get() !== null ? "true\n" : "false\n";
return $view;
}
$view = observer();
echo $view->get() === null ? "true\n" : "false\n";
Complete Swift comparison program, compiled from these files:
Token.swift
final class Token {}Functions.swift
func observer() -> () -> Bool {
let token = Token()
weak var view = token
print(view != nil)
return { [weak token] in token == nil }
}main.swift
let isGone = observer()
print(isGone())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 PHP 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