Switch 语句与模式匹配
Coddy 面向 Rust 开发者的 Swift 课程的第 11 课,共 48 课。
Rust 的 match 和 Swift 的 switch 都支持穷尽式模式匹配,包括元组、通配符部分和备选模式。原点分支必须放在范围更广的坐标轴备选模式之前,因为原点也位于坐标轴上。Rust 使用 | 分隔备选模式,并用通配符分支处理其余值;Swift 在这里用逗号分隔 case 模式,并使用 default。这两种结构都不会自动继续执行下一个分支。匹配可以在识别形状后绑定负载值,但所有权和借用会决定 Rust 的 match 是否会移动数据。Swift 的值和引用模型有所不同,因此要同时保留判断逻辑和所需的数据生命周期。
Rust
fn location(x: i32, y: i32) -> &'static str {
match (x, y) { (0, 0) => "origin", (0, _) | (_, 0) => "axis", _ => "plane" }
}
fn main() {
println!("{}", location(0, 0));
println!("{}", location(0, 5));
println!("{}", location(2, 3));
}
Swift
func location(_ x: Int, _ y: Int) -> String {
switch (x, y) {
case (0, 0): return "origin"
case (0, _), (_, 0): return "axis"
default: return "plane"
}
}
print(location(0, 0))
print(location(0, 5))
print(location(2, 3))挑战
简单实现 dayKind(_:)。输入是 -10 到 20 之间的整数。1 到 5 返回 work,6 或 7 返回 rest,其他所有值都返回 invalid。
实现必需的 API 和 solve(_ input: String) -> String。返回的输出文本末尾不要带换行符;不要在可编辑代码中打印。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后在返回的文本后准确打印一个换行符。所有数值运算都不会超出 Int 的范围。
你的代码写在 Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。
亲手试试
import Foundation
func apiChecks(_ input: String) -> Bool {
return dayKind(3) == "work" && dayKind(7) == "rest" && dayKind(-1) == "invalid"
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检查
let apiOK = apiChecks(input)
// 结束公开 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Rust 开发者的 Swift中的所有课
自己练习: Swift 在线编辑器