我正在我的网络层中借助 associatedType 和工厂创建通用解析器。基本目的是我只调用一个静态函数,我将传递类型和数据。它将完成所有解析工作,并将返回一个Parsed Model Object。
protocol Parsable: Codable {
associatedtype JSON
static func Parse(object: Data) -> JSON?
}
创建工厂
struct ParseFactory<object: Parsable> {
let type: RequestType
func doParsing(data: Data) -> object.JSON? {
switch type {
case .RequestOne:
return ModelOne.Parse(object: data) as? object.JSON
case .RequestTwo:
return ModelTwo.Parse(object: data) as? object.JSON
}
}
}
创建自己的解析内容的模型对象
class ModelOne: Parsable {
typealias JSON = ModelOne
let name: String
static func Parse(object: Data) -> JSON? {
let photoObject = try? JSONDecoder().decode(ModelOne.self, from: object)
return photoObject
}
}
class ModelTwo: Parsable {
typealias JSON = ModelTwo
let name: String
static func Parse(object: Data) -> JSON? {
let photoObject = try? JSONDecoder().decode(ModelTwo.self, from: object)
return photoObject
}
}
使用单行
从网络层呼叫
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) -> Void in
// parsing
if let dataNotNil = data {
// _ = Parsable
}
}
问题:如何调用将调用Model的相应功能的单行工厂函数。
注意:非常感谢任何帮助
答案 0 :(得分:0)
在这里您可以使用
let session = URLSession.shared
let request = URLRequest(url: URL(string:"yoururl")!)
let task = session.dataTask(with: request) { (data, response, error) -> Void in
if let dataNotNil = data {
let objectParse = ParseFactory<ModelOne>(type: RequestType.RequestOne)
let modelOneObjc = objectParse.doParsing(data: dataNotNil)
print(modelOneObjc?.name)
}
}
希望它有用