iosswift

'[ResponseData]' to expected argument type 'ResponseData'


I'm creating an application which are fetching data from an API. I've created the "API call" in a separate class so I can use the same call multiple times. But it does not return the value as I expect it to.

In ViewController A

    let data = JsonData.init()
    data.downloadJsonData(urlString: urlString) { (responseArray) in
        dataArray.append(responseArray)
        print(self.dataArray)
    }

I'm getting the error at dataArray.append(responseArray):

Cannot convert value of type '[ResponseData]' to expected argument type 'ResponseData'

In JsonData class

class JsonData{
    var dataArray:[ResponseData] = []

    func downloadJsonData(urlString: String, completed: @escaping (Array<ResponseData>) -> ()){

        guard let url = URL(string: urlString) else {return}

        URLSession.shared.dataTask(with: url) { (data, response, err) in
            guard let data = data else{
                return
            }
            do{
                self.dataArray = [try JSONDecoder().decode(ResponseData.self, from: data)]

                //Complete task in background
                DispatchQueue.main.async {
                    completed(self.dataArray)
                }
            }
            catch let jsonErr{
                print(jsonErr)
            }
        }.resume()
    }
}

I assume the problem is at:

DispatchQueue.main.async{
    completed(self.dataArray)
}

So I would like to return the array back to the correct class once it fetched the data from the API. What could I have done wrong? Any help would be much appreciated.


Solution

  • The error is clear: You are using the (wrong) API for appending a single element

    Replace

    dataArray.append(responseArray)
    

    with

    self.dataArray.append(contentsOf: responseArray)
    

    Side note:

    Setting and later appending the items again makes no sense. Use a local variable.

    Replace

    self.dataArray = [try JSONDecoder().decode(ResponseData.self, from: data)]
    
        //Complete task in background
        DispatchQueue.main.async {
            completed(self.dataArray)
        }
    

    with (a different name makes it clearer)

    let result = try JSONDecoder().decode(ResponseData.self, from: data)
    
        //Complete task in background
        DispatchQueue.main.async {
             completed([result])
        }