快速将结构作为函数参数传递

时间:2018-09-04 05:04:23

标签: swift

我有一个像这样的JSON解析类

class JSONParser: NSObject {
    let newJSONDecoder : JSONDecoder
    let data : Data

    init(decoder: JSONDecoder, data: Data, model:  ) {
        self.newJSONDecoder = JSONDecoder()
        self.data = data
    }
}

目标是使model参数成为可以接收任何数据和任何模型并创建对象并将其返回到调用类实例的类。 EG下方

let jsonParser = JSONParser(myDecoder, data, struct)
let parsedArray = jsonParser.createJSONArray()

我可以将结构传递给类型为struct而不是结构“类”名称类型的JSONParser初始化方法吗(例如ModelStruct)?

最终,应在该函数中使用struct参数

try newJSONDecoder.decode(model.self, from:data!),所以第二个问题是如何使它进入该函数-如果以字符串形式打印,将不起作用。

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

class JSONParser: NSObject {
    let newJSONDecoder : JSONDecoder
    let data : Data

    init<T: Codable>(data: Data, model: T.Type) {
        self.newJSONDecoder = JSONDecoder()
        do {
        let result = try self.newJSONDecoder.decode(model.self, from: data)
        print(result)
        } catch let err {
            print(err.localizedDescription)
        }
        self.data = data
    }
}

您的模型结构:

struct TestModel: Codable {
    let name: String
    let age: Int
}

您如何调用init:

let str = """
        {"name": "Robert", "age" : 35}
        """

    let data = str.data(using: .utf8)
    let jsonParser = JSONParser(data: data!, model: TestModel.self)

答案 1 :(得分:0)

这是我将通用Codable结构作为参数传递,并通过完成处理程序作为参数allGeneric返回它的方法:

func getAccordingToWebServiceFlag<T:Decodable>(flagSender: WebServicesFlagSenders,codableStruct: T.Type ,completionHandler: @escaping ( _ publicDataResponseModel:T?,_ flagSender: WebServicesFlagSenders) -> Void) {

excuteServerOperation(nil, imageData: nil, url:ServerAPIServant.webServiceFullURL(webServicesFlagSenders: flagSender), way: .get, flagSender: flagSender,completionHandler: { (result, flagSender) in
    AppDelegate().printStringBy_ispha(string: "  \(flagSender) Hmmm  \(result)")
    do {
        let jsonData = try JSONSerialization.data(withJSONObject:  result , options: .prettyPrinted)
        let decodableResponse = try! JSONDecoder().decode(codableStruct, from: jsonData)

        HelpingMethods.printCustomObjectBy_ispha(anyObject: decodableResponse as AnyObject)
        completionHandler(decodableResponse,flagSender)
    } catch let error {
        HelpingMethods.printStringBy_ispha(string: " Codable failure with error = \(error.localizedDescription)")
         completionHandler(nil,flagSender)
    }


}
)}