Menu
CoddyTech

协议与遵循

Coddy 面向 Rust 开发者的 Swift 课程的第 33 课,共 48 课。

Rust 的 trait 和 Swift 的协议用于声明行为,类型会显式实现或遵循这些行为。Rust 的 dyn trait 对象支持动态分派,但必须遵守 trait 的对象安全规则和引用生命周期。Swift 的 any Moving 是一种存在类型,可以存储遵循该协议的类型的值;而泛型约束会通过 API 保留特定的具体类型。源代码在 trait 对象引用后借用两个具体值,而目标数组存储存在类型的值。两者都要求提供相应行为,而不检查具体类型名称。结构体和类或其他受支持的类型一样,都可以实现这些契约;容器的所有权则与行为接口是彼此独立的问题。

Rust

trait Moving { fn movement(&self) -> &'static str; }
struct Bird;
struct Fish;
impl Moving for Bird { fn movement(&self) -> &'static str { "fly" } }
impl Moving for Fish { fn movement(&self) -> &'static str { "swim" } }

fn main() {
    let bird = Bird;
    let fish = Fish;
    let animals: Vec<&dyn Moving> = vec![&bird, &fish];
    println!("{}", animals.iter().map(|animal| animal.movement()).collect::<Vec<_>>().join(" "));
}

Swift

protocol Moving { func move() -> String }
struct Bird: Moving { func move() -> String { "fly" } }
struct Fish: Moving { func move() -> String { "swim" } }
let animals: [any Moving] = [Bird(), Fish()]
print(animals.map { $0.move() }.joined(separator: " "))
challenge icon

挑战

简单

实现协议 Rated,要求包含 rating: Int { get }。实现 Review: Rated,包含存储的 rating 和 init(rating:)。在 Functions.swift 中实现泛型函数 totalRating<T: Rated>(_ items: [T]) -> Int,对每个 rating 求和,包括其他符合该协议的类型的 rating。输入包含 0 到 50 个评分,每个评分为 0 到 5;输出总和。

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

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

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
struct ProbeRated: Rated { let rating: Int }
let custom = ProbeRated(rating: 4); return totalRating([custom, ProbeRated(rating: 2)]) == 6 && totalRating([Review(rating: 3)]) == 3 && totalRating([Review]()) == 0
}
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自我测试

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

面向 Rust 开发者的 Swift中的所有课

自己练习: Swift 在线编辑器