根据任务要求审查这段生成的注册表。
构建泛型键控注册表:替换已有值时不改变首次插入顺序;键缺失时返回 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)
}
}
生成代码仅作示例,不代表任何特定模型