元类型与泛型擦除:超越 Any 的运行时技巧
利用 Metatype 和 Existential 容器构建类型擦除容器,保留部分类型信息。 · 难度:入门 · +10XP
元类型与泛型擦除:超越 Any 的运行时技巧
Swift 的元类型(.Type)和 Existential 允许在运行时操作类型。本教程展示如何创建 type-erased wrapper,同时保留原始类型的比较和哈希能力。通过自定义 AnyEquatable 和 AnyHashable,你可以将不符合 Hashable 的类型存入集合,以及实现基于元类型的工厂模式。
protocol Animal {
associatedtype Food
func eat(_ food: Food)
}
struct AnyAnimal: Animal {
private let _eat: (Any) -> Void
private let _type: Any.Type
init(_ animal: T) {
self._type = T.self
self._eat = { food in
if let f = food as? T.Food {
animal.eat(f)
}
}
}
func eat(_ food: Any) { _eat(food) }
}