0

I am writing a Service class that will get data from a network layer and passes it to ViewModel. I have used completion handlers to pass data from the network layer. Now I am not sure how to pass this data from the Network layer to my view model. Following is my code in the Service layer:

    class HomeService {
        
        func getStates() -> [State]? {
            let urlString = baseURL + statesURL
            let params = ["user_id": UserDetails.getUserID() as AnyObject]
            
            NetworkOperations.fetchPostResponse(url: urlString, param: params, completionHandler: { (result) in
                switch(result) {
                case .Success(let res):
                    guard let response = res as? [String: AnyObject] else {
                        return
                    }
                    if let status = response["status"] as? Bool,
                       status,
                       let content = response["content"] as? [[String: AnyObject]] {
                        let array = content.map({ State(json: $0) })
                        return array
//error here: Unexpected non-void return value in void function
                    }
                    break
                case .Failure(_):
                    break
                }
            })
//error here: Missing return in a function expected to return '[State]?'
        }
    }

I have tried above but I am getting error:

Missing return in a function expected to return '[State]?'

And inside the handler where I try to return the array I get the following error:

Unexpected non-void return value in void function

Panks
  • 565
  • 1
  • 7
  • 20

1 Answers1

0

Your function getStates() is asynchronous. It can't return a value. Just like the NetworkOperations.fetchPostResponse() function takes a completion handler, your getStates() function needs to take a completion handler. Something like this:


func getStates(completion: StatesCompletion){
   //Your code to make the network call goes here
    case .Success(let res):
                    guard let response = res as? [String: AnyObject] else {
                    let error = MyError(statusInfo
                    completion(nil, error)
                    return
                    }
                    if let status = response["status"] as? Bool,
                       status,
                       let content = response["content"] as? [[String: AnyObject]] {
                        let array = content.map({ State(json: $0) })
                        completion(array, nil)
                      {
                    }
//...

See this article that I googled on the subject for more info.

Duncan C
  • 128,072
  • 22
  • 173
  • 272