这是使用类型擦除创建具有相关类型的协议数组的基本示例:
protocol ProtocolA {
associatedtype T
func doSomething() -> T
}
struct AnyProtocolA<T>: ProtocolA {
private let _doSomething: (() -> T)
init<U: ProtocolA>(someProtocolA: U) where U.T == T {
_doSomething = someProtocolA.doSomething
}
func doSomething() -> T {
return _doSomething()
}
}
创建它们的数组并不难:
let x: [AnyProtocolA<Any>] = []
有什么方法可以创建具有受约束的关联类型的约束的协议数组?这是我尝试过的:
protocol Validateable {
// I removed the functions and properties here to omit unreleveant code.
}
protocol ProtocolA {
associatedtype T: Validateable
func doSomething() -> T
}
struct AnyProtocolA<T: Validateable>: ProtocolA {
private let _doSomething: (() -> T)
init<U: ProtocolA>(someProtocolA: U) where U.T == T {
_doSomething = someProtocolA.doSomething
}
func doSomething() -> T {
return _doSomething()
}
}
它编译!但是,这是否没有击败现在创建AnyProtocolA数组的机会?现在,我无法在数组中使用Any类型作为占位符。
如何创建具有受限关联类型的 AnyProtocolA 数组?可能吗由于Any
当然不符合Validateable
,因此无法正常工作:
let x: [AnyProtocolA<Any>] = []
无法扩展任何内容:
extension Any: Validateable {} // Non nominal type error
编辑: 我想我已经找到了,只需键入擦除协议Validateable即可:
protocol Validateable {
// I removed the functions and properties here to omit unreleveant code.
}
protocol ProtocolA {
associatedtype T: Validateable
func doSomething() -> T
}
struct AnyProtocolA<T: Validateable>: ProtocolA {
private let _doSomething: (() -> T)
init<U: ProtocolA>(someProtocolA: U) where U.T == T {
_doSomething = someProtocolA.doSomething
}
func doSomething() -> T {
return _doSomething()
}
}
struct AnyValidateable<T>: Validateable {}
现在我可以将其用作:
let x: [AnyProtocolA<AnyValidateable<Any>>] = []
总是欢迎任何更好的答案:)