Menu
CoddyTech

Access Control and Invariants

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

Rust privacy is organized around modules, and a private field can be read through a public getter while mutation goes through checked methods. The nested module here prevents main from directly assigning position. Swift private(set) exposes a property read at its getter's access level while restricting the setter. Swift private, fileprivate and internal boundaries are not direct translations of Rust module visibility. Both cursor methods clamp the position at zero instead of allowing an invalid negative state. For the wallet task, validate the transition before changing related fields so a rejected operation preserves all required state.

Rust

mod cursor {
    pub struct Cursor { position: i32 }
    impl Cursor {
        pub fn new() -> Self { Self { position: 5 } }
        pub fn position(&self) -> i32 { self.position }
        pub fn back(&mut self, steps: i32) { self.position = 0.max(self.position - steps); }
    }
}

fn main() {
    let mut c = cursor::Cursor::new();
    c.back(9);
    println!("{}", c.position());
}

Swift

final class Cursor {
    private(set) var position = 5
    func back(_ steps: Int) { position = max(0, position - steps) }
}
let c = Cursor()
c.back(9)
print(c.position)
challenge icon

Challenge

Easy

Implement Wallet(initial:) with read-only-to-callers balance, and spend(_ amount: Int) -> Bool. Reject nonpositive or unaffordable spends without changing balance; otherwise subtract and return true. Initial balance is nonnegative. Input is initial balance 0 through 1000 followed by 0 through 30 spends -10 through 1000. Output final balance then one space then number of successful spends.

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 Wallet.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 w = Wallet(initial: 17); guard !w.spend(18) && !w.spend(0) && !w.spend(-1) && w.balance == 17 else { return false }; return w.spend(7) && w.balance == 10 && w.spend(10) && w.balance == 0 && !w.spend(1)
}
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