Classes and Shared Identity
Lesson 28 of 48 in Coddy's Swift for C Developers course.
C pointers can alias one struct object, while Swift classes provide language-level reference identity and ARC-managed lifetime. Assigning a Swift class reference shares the instance. Swift === tests identity, while == depends on applicable equality conformance rather than universally checking identity.
Both examples close one document through a second reference. The C object here has automatic storage that remains valid throughout the accesses. Swift let prevents rebinding the class reference but still permits methods to change mutable instance state. C pointer constness and pointed-to constness must be considered separately.
C: complete program
document.h
#ifndef DOCUMENT_H
#define DOCUMENT_H
#include <stdbool.h>
typedef struct { bool open; } Document;
static void document_close(Document *document) { document->open = false; }
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "document.h"
int main(void) {
Document document = {true};
Document *first = &document;
Document *second = first;
document_close(second);
printf("%s %s\n", first->open ? "true" : "false", first == second ? "true" : "false");
return 0;
}
Swift: complete program
Document.swift
import Foundation
final class Document {
private(set) var open = true
func close() { open = false }
}main.swift
import Foundation
let first = Document()
let second = first
second.close()
print("\(first.open) \(first === second)")A fixed Swift class binding is not deep immutability. Another reference can change the same instance and its observers see the result.
Challenge
EasyImplement Counter, a reference type with init(_ value: Int), read-only-to-callers value, and increment() adding one. Input is initial value -100 through 100 then count 0 through 20. Alias a counter, increment through the alias count times, and output the original value.
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 Counter.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 {
let a = Counter(5); let alias = a; let separate = Counter(5); alias.increment(); alias.increment(); return a === alias && a.value == 7 && separate.value == 5
}
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