Swift:协议符合条件中协议扩展的覆盖类型



所以,我正在尝试实现这一目标:

与Assocedtype有一个协议,他们将处理JSON解析的扩展。相关类型必须符合Decodable

protocol MyProtocol {
  associatedtype ResponseType: Decodable
  func handleResponse(data: Data) -> 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

我不知道是否有可能实现自己的尝试或正在以错误的方式接近。有人可以给我一些光吗?

谢谢。

我创建了相同的代码。这里有一些事实需要在这里理解。

extension MyProtocol {
    typealias ResponseType = MyDefaultDecodableType
    
    func handleResponse(data: Data) -> ResponseType {
        
        return try! JSONDecoder().decode(MyDefaultDecodableType.self, from: data)
        
    }
}

从概念上讲,Swift中没有通用协议。但是,通过使用typealias,我们可以为另一种类型声明所需的别名。

您的扩展名不需要定义typealias ResponseType = MyDefaultDecodableType,因为它将使用MyDefaultDecodableType提供一些默认实现,因此它是没有用的。

所以您的扩展名是这样的

extension MyProtocol {
  //  typealias ResponseType = MyDefaultDecodableType // NO NEED FOR IT
    
    func handleResponse(data: Data) -> MyDefaultDecodableType {
        print("Test (self)")
        return try! JSONDecoder().decode(MyDefaultDecodableType.self, from: data)
        
    }
}

现在您可以定义

class MyObject:MyProtocol {
    typealias ResponseType = AnotherDecodableType
    
    func handleResponse(data: Data) -> ResponseType {
        print("Test (self)")
        return try! JSONDecoder().decode(AnotherDecodableType.self, from: data)
        
    }
    
}
class MyObject2:MyProtocol {
   
    
}

没有任何错误

现在如果您使用

MyObject().handleResponse(data:data)
MyObject2().handleResponse(data:data2)

您会得到

测试__lldb_expr_44.myObject

测试__lldb_expr_44.myobject2

最新更新