protocol 模拟的 associated type 擦除?
解读
国内一面/二面常问,考察“能不能把带关联类型的协议当成普通类型用”。
Swift 的 associatedtype 属于泛型约束,协议本身无法直接作为变量类型(例如 let p: MyProtocol 编译失败)。
“擦除”就是手动构造一个“无泛型”的包装类型,把关联类型信息“藏起来”,让上层代码摆脱泛型传染,从而写出 let p: AnyMyProtocol 这种普通变量,同时保留运行时多态能力。
面试官想听:
- 为什么编译器报错;
- 手写类型擦除盒子的完整思路;
- 盒子如何转发调用、如何持有任意具体类型;
- 与 Swift 5.7
any Protocol的区别; - 实战场景(网络层、依赖注入、组件化路由)。
知识点
- associatedtype 的泛型本质:协议 witness table 中类型未确定,编译期无法计算内存布局。
- 类型擦除(Type Erasure)设计模式:
a. 抽象接口层(协议)
b. 私有盒子类(Box<Concrete>)
c. 公有包装结构(AnyXxx) - 类类型擦除 vs 结构体值类型擦除:类用继承+虚函数,结构体用泛型+inlining。
- 内存管理:盒子持有具体实例,ARC 保证生命周期;若需要共享,可升级为引用计数盒子。
- Swift 5.7 的
any Protocol语法糖:编译器自动生成擦除盒子,但自定义盒子仍可优化性能或增加额外行为(日志、线程安全检查)。 - 常见坑:
- Self 约束导致擦除失败;
- static 方法无法多态;
- 值类型复制带来的性能损耗。
答案
以网络请求抽象层为例,手写一个完整的类型擦除盒子:
// 1. 带关联类型的协议
protocol Request {
associatedtype Response: Decodable
var path: String { get }
func decode(from data: Data) throws -> Response
}
// 2. 私有擦除盒子基类(类类型保证同一 witness table)
private class _AnyRequestBox<Response: Decodable> {
var path: String { fatalError() }
func decode(from data: Data) throws -> Response { fatalError() }
}
// 3. 具体盒子,泛型参数 Concrete 保存真实类型
private final class _RequestBox<Concrete: Request>: _AnyRequestBox<Concrete.Response> {
private let concrete: Concrete
init(_ concrete: Concrete) { self.concrete = concrete }
override var path: String { concrete.path }
override func decode(from data: Data) throws -> Concrete.Response {
try concrete.decode(from: data)
}
}
// 4. 面向用户的无泛型包装
struct AnyRequest<Response: Decodable>: Request {
private let box: _AnyRequestBox<Response>
init<T: Request>(_ concrete: T) where T.Response == Response {
box = _RequestBox(concrete)
}
var path: String { box.path }
func decode(from data: Data) throws -> Response {
try box.decode(from: data)
}
}
// 5. 使用:上层代码完全摆脱泛型
struct UserRequest: Request {
typealias Response = User
let path = "/user"
func decode(from data: Data) throws -> User { try JSONDecoder().decode(User.self, from: data) }
}
let req: AnyRequest<User> = AnyRequest(UserRequest())
print(req.path) // "/user"
核心步骤总结:
- 把协议拆成“有泛型约束的协议”+“无泛型的包装类型”;
- 用私有类层级保存原始 witness table;
- 公有包装类型只暴露需要的方法,实现转发;
- 调用侧看到的只是
AnyRequest<User>,关联类型被“擦除”。
拓展思考
- 性能优化:
- 值类型请求体可用
@frozen+contiguousArray减少复制; - 使用
@inlinable让编译器跨模块内联转发函数,减小虚调用开销。
- 值类型请求体可用
- 结合 Swift Concurrency:
- 在擦除盒子里保存
async throws函数类型,实现AnyAsyncRequest,让旧模块也能调用新的 async 接口。
- 在擦除盒子里保存
- 与依赖注入框架结合:
- 在 Resolver 注册
AnyRequest<User>到容器,测试时注入 MockBox,实现无协议泛型的可替换性。
- 在 Resolver 注册
- 逆向思考:
- 若协议里出现
static func + Self约束,则无法擦除,需改回泛型参数或改用注册表模式; - 在 SwiftUI 中,
View的associatedtype Body已由AnyView提供官方擦除,但官方建议尽量少用,优先使用@ViewBuilder保持静态类型信息。
- 若协议里出现