lufei's Studio.

swift 类型擦除

字数统计: 240阅读时长: 1 min
2021/09/06 Share

平时开发过程中,可能有时候需要把拥有关联类型的协议对象作为属性的时候,这种情况下,最好的方案是使用「类型擦除」,平时我们在 swift 的官方源码中,也会看到类似 AnySequence 等等一些比较特殊的类型或者结构体,这其实就是官方提供的对类型擦除的运用。

参考官方实现,我们可以试试实现自己的协议的类型擦除中间类。

下面就是我尝试实现的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
protocol NJState {
associatedtype StateType
func add(_ item: StateType)
}

struct AnyNJState<StateType>: NJState {
init<Base: NJState>(_ base: Base) where Base.StateType == StateType {
_add = base.add
}
let _add: (StateType) -> Void
func add(_ item: StateType) {}
}

class StateDelegate<T> {

init(t:T) {
self.state = t
self.delegate = AnyNJState(States())
}
var state: T
var delegate: AnyNJState<T>

}

struct States<T>: NJState {
func add(_ item: T) {}
}

TypeErasure.swift

CATALOG