【发布时间】:2018-07-25 06:38:16
【问题描述】:
所以,我正在努力实现这一目标:
有一个带有关联类型的协议,它将处理 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
我不知道是否有可能实现我正在尝试的目标,或者我正在接近错误的方式。谁能给我点灯?
谢谢。
【问题讨论】:
-
您的 MyDefaultDecodableType 和 AnotherDecodableType 看起来如何?
-
AnotherDecodableType 和 MyDefaultDecodableType 正在确认
Decodable协议? -
感谢您的回答,我很高兴它对您有所帮助:) 祝您有美好的一天