Menu
CoddyTech

可选类型与绑定

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

C++17 的 std::optional<T> 可以存储一个 T 类型的值,也可以不存储任何值,这使得它与 Swift 的 Optional<Wrapped> 很适合进行对比。C++ 的 optional 可以在上下文中直接测试是否包含值,而 Swift 则需要使用可选绑定、模式匹配或显式的 nil 比较,而不是通用的 optional 真值判断。两者都能将实际存在的 0 与无值状态明确区分开来。在 C++ 中解引用未包含值的 optional 是无效操作,且调用 value() 会在无值时抛出异常;而 Swift 中对 nil 进行强制解包则会触发崩溃(trap)。当无值属于正常情况时,请显式使用默认回退值或绑定。Swift 的 Optional 既可以包装类引用也可以包装值,而 C++17 的 optional 无法直接用引用类型实例化。

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>

int main() {
std::optional<int> width;
    std::cout << width.value_or(80) << '\n';
    width = 24;
    if (width) std::cout << *width << '\n';
}

Swift

完整程序文件:main.swift。

var width: Int? = nil
print(width ?? 80)
width = 24
if let actual = width { print(actual) }
challenge icon

挑战

简单

实现 port(_:) -> Int?:仅在解析出的整数位于 1 到 65535 之间时返回该整数,否则返回 nil。输入为一个不超过 10 个字符的非空 ASCII 标记,包含十进制数字、可选的前导负号或字母。输出该值或 invalid。

实现所需的 API 和 solve(_ input: String) -> String。返回输出文本,结尾不要带换行符;不要在可编辑代码中打印。锁定的驱动代码会在额外的有效输入上独立检查 API,然后打印返回的文本并带有恰好一个换行符。所有数值运算均在 Int 范围内。

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

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
return port("443") == 443 && port("0") == nil && port("oops") == nil && port("65536") == 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 在线编辑器