审查生成的泛型注册表

来自 协议约束与存在类型
Swift 6.3.3 高级 6分钟 找出 4处问题

根据任务要求审查这段生成的注册表。

构建泛型键控注册表:替换已有值时不改变首次插入顺序;键缺失时返回 nil;绝不记录存储数据;平均查找时间为常数。

swift
protocol Lookup<Key, Value> {
    associatedtype Key: Hashable
    associatedtype Value
    func value(for key: Key) -> Value?
}
struct Registry<Key: Hashable, Value>: Lookup {
    private var entries: [(Key, Value)] = []
    mutating func put(_ value: Value, for key: Key) {
        print("storing \(key): \(value)")
        entries.append((key, value))
    }
    func value(for key: Key) -> Value? {
        entries.first(where: { $0.0 == key })!.1
    }
    func allValues() -> [Value] {
        entries.map(\.1)
    }
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误