Swift - 无法使用泛型转换类型的值

问题描述 投票:0回答:1

如何解决这个错误?

无法将类型'(ApiContainer,) - >()'的值转换为预期的参数类型'(ApiContainer <>?,错误?) - >()

Screenshot showing the error

来自服务器的JSON响应:

{
    "meta": {
        "sucess": "yes",
        "value": "123"
    },
    "result": [
        {
            "name": "Name 1",
            "postal_code": "PC1",
            "city": "City 1",
            "address": "01 Street"
        },
        {
            "name": "Name 2",
            "postal_code": "PC2",
            "city": "City 2",
            "address": "02 Street"
        }
    ]
}

结构

struct Client: Decodable {
    let name: String
    let postal_code: String
    let city: String
}

struct Meta: Decodable {
    let sucess: String
    let value: String
}

struct ApiContainer<T: Decodable>: Decodable
    let meta: Meta
    let result: [T]
}

我有一个函数'getAll',它应该发出请求并返回相应的结构(ApiContainer,其中T可以是例如Client)

func getAll() {
    makeRequest(endpoint: "http://blog.local:4711/api/all", completionHandler:
        {(response: ApiContainer<Client>, error) in
            if let error = error {
                print("error calling POST on /todos")
                print(error)
                return
            }
            print(result)

            //self.tableArray = decodedData.result

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        } )
    }

从getAll()调用函数makeRequest

func makeRequest<T>(endpoint: String, completionHandler: @escaping (ApiContainer<T>?, Error?) -> ()) {
    guard let url = URL(string: endpoint) else {
        print("Error: cannot create URL")
        let error = BackendError.urlError(reason: "Could not create URL")
        completionHandler(nil, error)
        return
    }

    let urlRequest = URLRequest(url: url)
    let session = URLSession.shared

    let task = session.dataTask(with: urlRequest, completionHandler: {
        (data, response, error) in
        guard let responseData = data else {
            print("Error: did not receive data")
            completionHandler(nil, error)
            return
        }
        guard error == nil else {
            completionHandler(nil, error!)
            return
        }

        do {
            let response = try JSONDecoder().decode(ApiContainer<T>.self, from: responseData)
            completionHandler(response, nil)
        }
                catch {
                    print("error trying to convert data to JSON")
                    print(error)
                    completionHandler(nil, error)
                }
    })
    task.resume()
}
json swift generics
1个回答
0
投票

在泛型的情况下,您必须明确地在闭包中注释类型以指定泛型的静态类型

makeRequest(endpoint: "http://blog.local:4711/api/all", 
            completionHandler: { (container : ApiContainer<Client>?, error : Error?) in ...
© www.soinside.com 2019 - 2024. All rights reserved.