gpt4 book ai didi

swift - 具有通用协议(protocol) swift 的工厂

转载 作者:行者123 更新时间:2023-11-28 07:54:29 26 4
gpt4 key购买 nike

我在 associatedTypeFactory 的帮助下在我的网络层中创建了一个通用解析器。基本目的是我将只调用一个静态函数,我将向其传递类型和数据。它将执行所有解析工作并返回一个已解析的模型对象。

protocol Parsable: Codable {
associatedtype JSON
static func Parse(object: Data) -> JSON?
}

Creation of Factory

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
}
}
}

Model Objects that create their own parsing stuff

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
}
}

Call from Network Layer with single Line

    let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) -> Void in
// parsing
if let dataNotNil = data {
// _ = Parsable
}
}

Question: How can I call the one line factory function that will call the respective function of Model.

注意:任何帮助将不胜感激

最佳答案

在这里你可以如何使用

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)
}
}

希望对你有帮助

关于swift - 具有通用协议(protocol) swift 的工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48684541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com