通用解码功能不起作用(快速)

时间:2018-11-07 06:22:55

标签: swift generics decoder decodable jsondecoder

我正在尝试创建一个通用的解码函数来解码我的两个不同模型。我收到错误“参数类型'PrivateSchoolType.Type'与预期类型'Decodable'不符”。

型号

struct PrivateSchoolModel: Decodable {
    var name: String
    var id: String
    var city: String
    var state: String
}

呼叫功能

function getInfo() {
    // does not work => ERROR
    guard let schools = decode(jsonData: jsonData, using: PrivateSchoolModel) else { return }

    // does work
    guard let schools = specificDecode()
}

特定解码功能(可以完成)

private func specificDecode() -> [PrivateSchoolModel]? {
    guard let jsonData = getJSONData(from: .privateSchool) else { return }
        do {
            let decoder = JSONDecoder()
            let schools = try decoder.decode([PrivateSchoolModel].self, from:
            jsonData)
            return schools

        } catch let error {
            print("Error: \(error.localizedDescription)")
        }
        return nil
}

通用解码功能(无效)

private func decode<M: Decodable>(jsonData: Data, using model: M) -> [M]? {
        do {
            //here dataResponse received from a network request
            let decoder = JSONDecoder()
            let schools = try decoder.decode([M].self, from:
                jsonData) //Decode JSON Response Data

            return schools
        } catch let parsingError {
            print("Error", parsingError)
        }

        return nil
    }

1 个答案:

答案 0 :(得分:1)

如下更改方法signature

private func decode<M: Decodable>(jsonData: Data, using modelType: M.Type) -> M? {
    do {
        //here dataResponse received from a network request
        let decoder = JSONDecoder()
        let schools = try decoder.decode(modelType, from: jsonData) //Decode JSON Response Data
        return schools
    } catch let parsingError {
        print("Error", parsingError)
    }
    return nil
}

用法

guard let schools = decode(jsonData: jsonData, using: [PublicSchoolModel].self) else { return }