Menu
CoddyTech

guard 语句与提前退出

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

C++ 通常会在检查输入无效或不存在后提前返回。Swift 的 guard 用于表达剩余作用域的前置条件,并要求其 else 分支离开该作用域。成功后,guard-let 绑定仍然可用;而 if-let 绑定仅限于其成功分支内。源代码使用 std::optional<std::string>,并通过大写转换处理 ASCII 小写字符,而目标代码的 uppercased 操作支持更广泛的 Unicode 行为。显示的 ASCII 单词转换结果一致。guard 不是异常处理程序,也不一定要解包可选值;它可以检查任何布尔不变量。

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>
std::string render(std::optional<std::string> input) {
    if (!input) return "untitled";
    std::string text = *input;
    for (char &c : text) if (c >= 'a' && c <= 'z') c = static_cast<char>(c - 'a' + 'A');
    return text;
}

int main() {
std::cout << render(std::nullopt) << '\n';
    std::cout << render(std::string("go")) << '\n';
}

Swift

完整程序文件:Functions.swift。

func render(_ input: String?) -> String {
    guard let caption = input else { return "untitled" }
    return caption.uppercased()
}

完整程序文件:main.swift。

print(render(nil))
print(render("go"))
challenge icon

挑战

简单

实现 remainder(balance:withdrawal:):如果取款金额小于或等于 0,或超过余额,则拒绝取款;否则返回剩余余额。输入中的余额范围为 0 到 10000,取款金额范围为 -100 到 10000。输出剩余余额,或 rejected。

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

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

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
return remainder(balance: 19, withdrawal: 4) == 15 && remainder(balance: 19, withdrawal: 0) == nil && remainder(balance: 19, withdrawal: 20) == nil
}
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 在线编辑器