I am trying to write a generic parser method which will parse data with respect to return type.
Edit
We get complex json response from multiple servers. Sometimes same response model could mean different things or vice versa. My target is to inject parsers to my repositories/services. And get the same result at the end.
Edit End
Edit 2
For "FeedTypeSerializable" custom init method should be called
For "FeedTypeDecodable" should be called.
Edit 2 End
protocol FeedResponseProtocol {
var feed : String { get }
var success : Bool { get }
}
protocol Serializable {
init(_ json : [String:Any])
}
Structure which could be constructed using JSON object
struct FeedTypeSerializable : FeedResponseProtocol, Serializable {
var feed: String
var success: Bool
init(_ json: [String : Any]) {
feed = ""
self.success = false
}
}
Decodable Struct
struct FeedTypeDecodable : FeedResponseProtocol {
var feed: String
var success: Bool
}
extension FeedTypeDecodable : Decodable {
private enum CodingKeys : String, CodingKey {
case feed, success
}
}
Finally my parser protocol and implementation. I am getting two different error for trying two different things
1: Error : Cannot convert value of type 'Decodable?' to expected argument type 'T.Type' I want to know how I could cast one protocol to another, if possible
2: Error : Static member 'init' cannot be used on instance of type 'Serializable'
protocol ParserProtcol {
func getFeed<T : FeedResponseProtocol>(forData data: Data) -> T
}
struct FeedParser : ParserProtcol {
func getFeed<T>(forData data: Data) -> T where T : FeedResponseProtocol {
if T.self is Decodable {
let response : T = JSONDecoder().decode((T.Type as? Decodable), from: data)
// 1: Error
}
else if T.self is Serializable {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
let response = (T as! Serializable).init(jsonObject)
//2: Error shown
}
catch {
//error handling
}
}
}
}