2

Using Swift I can do a callback like the following:

userService.validateToken("6beba35f", success: onSuccess, failure: onFailure)

func onSuccess(status_code: Int, data: String)
{
    var dd : String = ""
}

func onFailure(status_code: Int, data: String)
{
    var dd : String = ""

}

but i would like to have the functions on the same line as the call:

Example 1:

userService.validateToken("6beba35f",
        success: (Int, String) -> ()
            {
        },
        failure: (Int, String) -> ()
            {
    })

Example 2:

userService.validateToken("6beba35f",
        success: (Int, String)
            {
        },
        failure: (Int, String)
            {
        })

both give errors. I think im close with Example 1 but it keeps giving me an error "Expected , seperator" and when i have it add the ","

success: (Int, String), -> () but the error keeps saying "Expected , separator"

Any ideas on what the solutions is?

Including function

func validateToken(token: String, success: (Int, String) -> Void, failure: (Int, String) -> Void)
{
    if(Network.isOnline())
    {
        var url: String = Commons.plistValue("Base URL") + "/security/" + token

        Alamofire.request(.GET, url)
            .responseJSON { (request, response, json, error) in

                let jsonData: JSON = JSON(json!)
                let statusCode: Int = response!.statusCode

                if(statusCode == 202)
                {
                    success(statusCode, jsonData["status"]["message"].stringValue)
                }
                else
                {
                    failure(statusCode, jsonData["status"]["message"].stringValue)
                }
            }
    }
    else
    {
        failure(-1, "No Internet Connection")
    }

}

Usage Fix

    userService.validateToken("6beba35f",
        success: { status_code, data in
            (
                println(status_code)
            )

        },
        failure: { status_code, data in
            (
                println(status_code)
            )
    })
adviner
  • 3,295
  • 10
  • 35
  • 64

1 Answers1

2

There are several ways to declare or use closures. The simplest one you're looking for is probably:

{ status_code, data in
    println(status_code)
}

This needs to be used in such a way that the compiler can infer the type of status_code, data, and determine that there should be no return value. For instance, you can pass it as a function parameter (what you want), or assign it to a variable with appropriate type hints.

zneak
  • 134,922
  • 42
  • 253
  • 328
  • Thank you for the link also helps tons :) – adviner Apr 28 '15 at 21:21
  • I have a similar question here I'm still trying to figure out, it has an open bounty if anyone wants to take a stab at it: http://stackoverflow.com/questions/29871633/how-would-i-create-a-callback-around-an-xml-request – Dan Beaulieu Apr 28 '15 at 21:33