Menu
CoddyTech

ARC and Weak References

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

Rust normally destroys owned values when ownership ends, and Rc extends an allocation's lifetime until its last strong owner is dropped. Drop implements cleanup for Resource here. Swift ARC similarly retains class instances through strong references and runs deinit after their ownership ends. The explicit optional assignments remove two owners in order, so the release occurs only after the second is cleared. Strong Rc cycles and strong Swift class cycles can both retain objects unexpectedly. Rust Weak::upgrade returns an optional strong Rc owner on success, while the Weak itself does not retain; a Swift weak reference is optional and becomes nil after deallocation. Neither weak observer is a substitute for a required strong owner.

Rust

struct Resource;
impl Drop for Resource { fn drop(&mut self) { println!("released"); } }

fn main() {
    let mut owner = Some(std::rc::Rc::new(Resource));
    let mut alias = owner.clone();
    owner = None;
    println!("{}", alias.is_some());
    alias = None;
    let _ = (owner, alias);
}

Swift

final class Resource {
    deinit { print("released") }
}
var owner: Resource? = Resource()
var alias = owner
owner = nil
print(alias != nil)
alias = nil
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 Rust Developers

Practice on your own: Swift playground