Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write block functions in Swift

How would I write this block function in swift. I've read through on the subject but the syntax just doesn't make much sense to me.

MyAppRequest *request = [_agent login];
    [request sendWithLoadMessage:@"Signing In"
    successMessage:@"Signed In"
    failureMessage:@"Failed to log in"
    recoveryOptions:@"If you keep having trouble, try going to http://mystrou.firehosehelp.com and try loggin in there. If that fails, try resetting your password"
    success:^(MyAppResponse *response) {
        PREFS.authToken = _agent.accessToken;
        [_delegate loginViewController:self loggedInAgent:_agent];
    } failure:^(MyAppResponse *response) {

    }];
like image 248
YichenBman Avatar asked Oct 01 '14 04:10

YichenBman


1 Answers

It's not that hard actually. called closures in Swift).

public func someFunction(success: (response: AnyObject!) -> Void, failure: (error: NSError?) -> Void) {

}

And here's how you call it.

someFunction(success: { (response) -> Void in
    // Handle success response
}) { (error?) -> Void in
    // Do error handling stuff
}

In your case, I'm getting this block handles some server response. Most probably logging in. The success block would be called if the network operation succeeds. Inside it, you save the received access token from your server.

The failure block is called if the network request fails. You might want to log the error out, display an alert to the user stuff like that in it.

If you're confused about the syntax I suggest refer to these two sites. For Objective-C block syntax and for Swift closure syntax.

like image 103
Isuru Avatar answered Sep 28 '22 00:09

Isuru