Menu
CoddyTech

Classes and Shared Identity

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

Rust makes shared ownership and interior mutability explicit here with Rc<RefCell<Lamp>>. Rc::clone adds another strong owner, and RefCell checks borrowing at runtime before mutation. Rc::ptr_eq compares allocation identity. Swift class references share an instance directly, and === compares identity. A let class reference can still call an accessible mutating method because the binding is fixed, not the object's properties. Both programs toggle the shared lamp and leave a separately allocated lamp off. Neither design supplies automatic thread safety: Rc is single-threaded, and ordinary Swift class sharing needs its own concurrency discipline.

Rust

struct Lamp { on: bool }
impl Lamp { fn toggle(&mut self) { self.on = !self.on; } }

fn main() {
    let original = std::rc::Rc::new(std::cell::RefCell::new(Lamp { on: false }));
    let alias = std::rc::Rc::clone(&original);
    let other = std::rc::Rc::new(std::cell::RefCell::new(Lamp { on: false }));
    alias.borrow_mut().toggle();
    println!("{} {} {}", original.borrow().on, other.borrow().on, std::rc::Rc::ptr_eq(&original, &alias));
}

Swift

final class Lamp {
    var on = false
    func toggle() { on = !on }
}
let original = Lamp()
let alias = original
let other = Lamp()
alias.toggle()
print(original.on, other.on, original === alias)
challenge icon

Challenge

Easy

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