符合协议的更多指定扩展版本

问题描述 投票:0回答:1

假设存在用于限制类型的空协议:

public protocol DataType { }

protocol Parser {
    func parseData<T: DataType>(_ data: Data, to: T.Type) throws -> T
}

所以我们需要专门用于解析JSON对象的解析器:

typealias DecodableDataType = Decodable & DataType

protocol JSONParser: Parser {
    var jsonDecoder: JSONDecoder { get }
    func parseData<T: DecodableDataType>(_ data: Data, to: T.Type) throws -> T
}

所以它也与parser需求相匹配,并且由于已经定义了jsonDecoder,所以简单的extension会很棒:

extension JSONParser {
    func parseData<T: DecodableDataType>(_ data: Data, to: T.Type) throws -> T { try jsonDecoder.decode(T.self, from: data) }
}

因此,如果我们为此实现一个管理器类:

class JSONParsingManager: JSONParser {
    public var jsonDecoder: JSONDecoder

    init(jsonDecoder: JSONDecoder) {
        self.jsonDecoder = jsonDecoder
    }
}

期待一切自动进行,但会抛出:

类型'JSONParsingManager'不符合协议'解析器'

我错过了什么?我需要为其他序列化程序(例如Protobuf解析器等)定义管理器,因此我不能只是一开始就遵循Decodable


更多澄清:

另一个应以相同方式工作的协议:

protocol ProtobufParser: Parser {
    func parseData<T: Message>(_ data: Data, to: T.Type) throws -> T
}

extension ProtobufParser {
    func parseData<T: Message>(_ data: Data, to: T.Type) throws -> T { try T.init(serializedData: data) }
}

更新

我无法定义独立协议,因为有一个函数需要获取任何种类的Parser才能解析任何可解析的对象。

swift protocols
1个回答
0
投票

错误消息是正确的。该协议的要求是

© www.soinside.com 2019 - 2024. All rights reserved.