【发布时间】:2019-08-22 07:32:53
【问题描述】:
我需要将实现具有关联类型的协议的对象传递给接受协议的方法。这在 Swift(直到最新的 Swift 5)中是不可能的,所以我使用类型擦除和基于 this blog 的影子协议。
protocol ShadowA {
func test(data: Any) -> String
}
extension ShadowA {
func test(data: Any) -> String {
return "shadow"
}
}
protocol A: ShadowA {
associatedtype AT
func test(data: AT) -> String
}
class SpecificA: A {
typealias AT = Int
func test(data: Int) -> String {
return "specific"
}
}
问题是当我将对象传递给方法时,会调用“影子的默认实现”而不是“通用”的。您可以查看playground 以了解发生了什么。
有什么问题吗?或者这个用例在 Swift 中根本不可能?
【问题讨论】:
标签: swift protocols swift-protocols associated-types