How to guarantee the type of value returned by a closure?

0

I can perform the requests with Alamofire, but I saw that it is not possible to use return within the scope of success.

After a search, I saw that the solution is to use a closure pattern, to get the value of the request when it is finished, so I implemented the following code:

// Em qualquer lugar do codigo faço a chamada
    func pegaNaAPI(){

        var valor = realizaRequisicao("chinelo", "vassoura", completionHandler: { (result, error) -> MeuModel in

            return result!

        })

       if valor.soma = 0 {

            print("É de graça!")

        }


    }

    =================

    // Implementacao para realizar requisicao

    func realizaRequisicao(paramA : String, paramB: String, completionHandler: (result:MeuModel?, error:NSError?) -> MeuModel) {

        makeCall(paramA, paramB, completionHandler: completionHandler)

    }



    func makeCall(paramA : String, paramB: String, completionHandler: (result:MeuModel?, error:NSError?) -> MeuModel){


        Alamofire.request(.GET, urlRequisicao, parameters: nil).responseJSON {  response in

            switch response.result {

            case .Success(let data):

                completionHandler(result: data as? NSDictionary, error: nil)

                break

            case .Failure( _):

                completionHandler(result: data as? NSDictionary, error: nil)

                break

            }
        }

    }

Then I did another search, and saw that closures can perform 'return' data.

In this code snippet you have a problem:

if valor.soma == 0 {

    print("É de graça!")

 }

The error message I get is:

  

Value of tuple type '()' has no member 'sum'

How can I ensure the type of the returned value? Because soma property is present in MeuModel

    
asked by anonymous 24.04.2016 / 06:48

1 answer

0

The idea when you have a method with a completion handler block is not to return the result, as Leo Dabus commented. You can call a method of delegate, or use NSNotification with userInfo to pass the value returned to the relevant object. Or, if your valor variable was external to the method, you could assign the result to it within the block. Another important thing is that, for many reasons, the result to be nil, calling result! will crash in that case. You can test with guard , if let or simply test if result != nil { self.valor = result } But most importantly, do not put the return inside the completion handler.

    
30.04.2016 / 02:27