Menu
CoddyTech

访问控制与不变量

Coddy 面向 C++ 开发者的 Swift 课程 课程的第 39 课,共 48 课。

C++ 中,private 成员配合 public const getter,可以在隐藏修改操作的同时开放读取。Swift 的 private(set) 同样将读取权限与设置权限分开,而 private、fileprivate、internal、public 和 open 这几个级别则依据 Swift 的声明、文件和模块边界来控制访问。C++ 的 private 和 protected 遵循类规则,而不是 Swift 的模块可见性规则。两个示例都只在文本发生变化时增加版本号,因此重复进行相同的更新不会破坏这一不变量。const getter 是一种方法契约,并不保证对象整体始终不可变。让负责修改的操作同时更新相关字段。

C++

完整程序文件: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

完整程序文件: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
    }
}

完整程序文件:main.swift。

var draft = Draft()
draft.replace("hello")
draft.replace("hello")
print(draft.revision)
challenge icon

挑战

简单

实现 Wallet(initial:),其中 balance 仅可由调用者读取,并实现 spend(_ amount: Int) -> Bool。如果支出金额小于或等于零,或超出可用余额,就拒绝支出且不更改余额;否则扣除相应金额并返回 true。初始余额为非负数。输入依次为初始余额(0 到 1000)以及 0 到 30 笔支出(-10 到 1000)。输出最终余额,后接一个空格,再接成功支出的次数。

实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印内容。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后将返回的文本打印出来,并且恰好添加一个换行符。所有数值运算都在 Int 的范围内。

你的代码写在 Wallet.swift 和 Functions.swift 中。main.swift 包含提供的输入输出代码,不能编辑。

亲手试试

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)!
// 开始公开 API 检查
let apiOK = apiChecks(input)
// 结束公开 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C++ 开发者的 Swift 课程中的所有课

自己练习: Swift 在线编辑器