N
N
nastya_zholudeva2018-05-22 16:50:58
Swift
nastya_zholudeva, 2018-05-22 16:50:58

How to make a function return values ​​of type Array?

I want to make a universal function that would make a request to the API. Actually, here she is.

func request(uri: String, params: Dictionary<String, Any>) -> Array<Dictionary<String, String>> {
        Alamofire.request(self.url + uri, method: .get, parameters: params as! Parameters).responseJSON { response in
            if let json: [AnyObject] = response.result.value as? [AnyObject] {
                var items = [Dictionary<String, String>]()
                let data = JSON(json)
                for item in data {
                    items.append(["id": item.1["id"].stringValue, "title": item.1["title"].stringValue])
                }
                return items
            }
        }
    }

But this code throws an error Unexpected non-void return value in void function. How can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
doublench21, 2018-05-22
@nastya_zholudeva

Well, you probably just forgot or don't understand that the responseJson function is executed asynchronously. This is just a callback that will be executed when the server returns Json for your request. But since the function works asynchronously in another thread, there is nothing on the current thread after the request to the server. And the function terminates. But it does not return anything, and you indicated that it should return something. Hence the error about non Void.
The fact that you are returning item is good. The current it returns is no longer in this function.
If you want this function to return a server response, then you need to somehow wait for a response from the asynchronous function. Can use DispatchGroup and wait.
In general, you don't need to do that. The whole point of asynchrony will be gone. This function should not return anything. And the very fact that the data has arrived should be processed in responseJson or in the variable observer where you assign what you get.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question