swift 范型之类型擦除

泛型的本质是 在编译时进行类型特化(Monomorphization),即:

  1. 编译器并不会直接生成通用的 T 类型代码
  2. 在编译时,Swift 会根据实际传递的类型生成对应的代码,类似于 C++ 的模板展开。
  3. 如果多次调用泛型函数,但参数类型不同,编译器会为每种类型生成一份具体实现

 

在 Swift 中,泛型协议不能直接用于变量。如果你想存储 不同泛型类型,可以使用 类型擦除模式(Type Erasure)。

protocol Shape {
    func area() -> Double
}

// 泛型包装类,隐藏泛型类型,让 shapes 数组可以存储不同的 Shape 类型。
class AnyShape<T: Shape>: Shape {
    private let _area: () -> Double

    init<U: Shape>(_ shape: U) where U == T {
        _area = shape.area
    }

    func area() -> Double {
        return _area()
    }
}

struct Circle: Shape {
    var radius: Double
    func area() -> Double { return .pi * radius * radius }
}

struct Square: Shape {
    var side: Double
    func area() -> Double { return side * side }
}

// ✅ 允许存储不同 Shape 类型
let shapes: [AnyShape<Shape>] = [AnyShape(Circle(radius: 5)), AnyShape(Square(side: 4))]

for shape in shapes {
    print(shape.area())
}

  

posted @ 2025-02-05 11:58  程石亮  阅读(19)  评论(0编辑  收藏  举报