Menu
CoddyTech

Access Control and Invariants

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

C++ private members with a public const getter can expose observation while keeping mutation behind methods. Swift private(set) similarly separates read access from setter access, and its private, fileprivate, internal, public and open levels use Swift declaration, file and module boundaries. C++ private and protected follow class rules rather than Swift module visibility. Both examples increase revision only when text changes, preserving the invariant for a repeated identical update. A const getter is a method contract and not a universal deep-immutability guarantee. Keep the mutation operation responsible for updating related fields together.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
class Draft {
    std::string text;
    int revision_ = 0;
public:
    int revision() const { return revision_; }
    void replace(const std::string &value) { if (value == text) return; text = value; ++revision_; }
};

int main() {
Draft draft;
    draft.replace("hello");
    draft.replace("hello");
    std::cout << draft.revision() << '\n';
}

Swift

Complete program file: Draft.swift.

struct Draft {
    private var text = ""
    private(set) var revision = 0
    mutating func replace(_ value: String) {
        guard value != text else { return }
        text = value
        revision += 1
    }
}

Complete program file: main.swift.

var draft = Draft()
draft.replace("hello")
draft.replace("hello")
print(draft.revision)
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 C++ Developers

Practice on your own: Swift playground