Menu
CoddyTech

ARC and Weak References

Lesson 29 of 48 in Coddy's Swift for JavaScript Developers course.

JavaScript closures can keep objects reachable through captured references. Clearing owner does not remove the separate panel binding retained by read, so both calls still return ready. Garbage collection follows reachability, and WeakRef observations or finalization should not be used to promise an exact collection instant.

Swift ARC manages strong class ownership, and the target reader deliberately captures its panel weakly so it can report gone after ownership ends. Strong reference cycles can prevent release. Choose weak when absence is valid; choose unowned only when the lifetime relationship guarantees validity at every access. A naming convention does not make a capture weak.

JavaScript

Complete JavaScript console program:

main.js

class Panel { title = "ready"; }
function reader(panel) { return () => panel.title; }
let owner = new Panel();
const read = reader(owner);
console.log(read());
owner = undefined;
console.log(read());

Swift

Complete program; compile the listed files together:

Panel.swift

import Foundation
final class Panel { var title = "ready" }

main.swift

import Foundation
var owner: Panel? = Panel()
let read = { [weak owner] in owner?.title ?? "gone" }
print(read())
owner = nil
print(read())
challenge icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for JavaScript Developers

Practice on your own: Swift playground