所以,我正在努力实现这个目标:
有一个协议类型的协议谁将处理json解析到他的扩展 . 关联类型必须符合 Decodable
:
protocol MyProtocol {
associatedtype ResponseType: Decodable
func handleResponse(data: Data) -> ResponseType
}
我想要做的是将responseType的默认类型设置为我的扩展,然后,如果需要,将该类型重写为类或结构一致性 . 像这样的东西 .
extension MyProtocol {
typealias ResponseType = MyDefaultDecodableType
func handleResponse(data: Data) -> ResponseType { ... }
}
class MyObject: MyProtocol {
typealias ResponseType = AnotherDecodableType
}
问题是我在 MyObject
中收到这样的错误:
error: type 'MyObject' does not conform to protocol 'MyProtocol'
class MyObject: MyProtocol {
^
note: multiple matching types named 'ResponseType'
associatedtype ResponseType: Decodable
^
note: possibly intended match
typealias ResponseType = AnotherDecodableType
^
note: possibly intended match
public typealias ResponseType = MyDefaultDecodableType
我不知道是否有可能实现我正在尝试的东西,或者我正在接近错误的方式 . 谁能给我点亮一些?
谢谢 .
1 回答
我创建了相同的代码 . 这里有一些事实需要理解 .
从概念上讲,Swift中没有通用协议 . 但是通过使用
typealias
,我们可以为另一种类型声明一个必需的别名 .您的扩展不需要定义
typealias ResponseType = MyDefaultDecodableType
,因为它将使用MyDefaultDecodableType
提供一些默认实现,因此它是无用的 .所以你的扩展将是这样的
现在你可以定义了
没有任何错误
现在,如果你使用
你会得到