Search code examples
iosswiftcompletionhandlermoya

Swift networking with non-void completion handler gets error


My goal is to set up a completion handler using a standard Moya request call.

Here is my process:

  1. Call backend with with a MoyaProvider that conforms to my own BackendAPI (already set up)
  2. Wrap this call in a completion handler to return [Player] data (Player is a custom class in the project)
  3. Display [Player] data

Here is the actual code:

func getPlayers(orchestraId: String, finished: @escaping () -> [Player]) {
    let provider = MoyaProvider<BackendAPI>()
    provider.request(.getPlayers(orchestraId: orchestraId)) { (result) in

        switch result {
        case let .success(moyaResponse):

            let statusCode = moyaResponse.statusCode
            if statusCode == 200 {
                let data = moyaResponse.data
                let json = JSON.init(data: data)

                let players: [Player] = self.deserializeJSONPlayers(with: json)

                return players

            } else {
                print ("Non 200 for league players data")
                self.debugStatementsFromResponse(response: moyaResponse)
            }

        case let .failure(error):
            print ("Error: \(error)")

        }
    }
}

I am getting an error on the return line, with the note that Unexpected non-void return in void function. However, I have declared my function to be a non-void function. What I am doing incorrectly in structuring my method?


Solution

  • You have the completionHandler which you should use if you want to return the value with the current syntax. If you want to use return players then you must change the syntax.

    Use this syntax instead to make your current code work with the completionHandler:

    func getPlayers(orchestraId: String, finished: @escaping ([Player]) -> Void) { 
        finished(players) // Instead of return players
    }