ARC and Weak References
Lesson 29 of 48 in Coddy's Swift for C Developers course.
C pointer assignment does not install reference counting or automatically manage allocation lifetime. This example uses an automatic Session object that stays alive in its enclosing scope regardless of resetting one pointer. Heap allocations instead need an explicit ownership and release policy. Swift ARC manages class lifetime through strong references.
Swift weak references do not retain their class instance and become nil when it deallocates. They use mutable optional references. Safe unowned references also do not retain, but accessing one after its instance disappears traps. Strong cycles can keep unused objects alive and must be addressed through the ownership design.
The C observer is an ordinary pointer, not a self-zeroing weak reference. It is safe here because the automatic object is still alive. In the target, a strong keeper preserves the session while the weak observer reads it. The two programs print the same name through different lifetime guarantees.
C: complete program
session.h
#ifndef SESSION_H
#define SESSION_H
typedef struct { const char *name; } Session;
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "session.h"
int main(void) {
Session session = {"canvas"};
Session *owner = &session;
Session *keeper = owner;
Session *observer = owner;
owner = NULL;
puts(observer->name);
(void)owner;
(void)keeper;
return 0;
}
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") }Never inspect a C dangling pointer as though it had automatically become NULL. Swift weak nil handling is a specific runtime-supported ownership feature.
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 C 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