在Swift中编写块函数

时间:2014-10-01 04:25:13

标签: objective-c function swift objective-c-blocks

我如何在swift中编写这个块函数。我已经仔细阅读了这个主题,但语法对我来说没有多大意义。

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) {

    }];

2 个答案:

答案 0 :(得分:19)

实际上并不难。在Swift中调用闭包。)

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

}

以下是你如何称呼它。

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

在你的情况下,我得到这个块处理一些服务器响应。最有可能登录。如果网络操作成功,将调用success块。在其中,您可以从服务器保存收到的访问令牌。

如果网络请求失败,则调用failure块。您可能希望记录错误,向用户显示类似其中的警告。

如果您对语法感到困惑,我建议您参考这两个网站。适用于Objective-C block syntaxSwift closure syntax

答案 1 :(得分:0)

感谢@isuru我想出了这个:

let request: MyAppRequest = agent .login()

request .sendWithLoadMessage("Signing in",
        successMessage: "Signed in",
        failureMessage: "Failed to login",
        recoveryOptions: "Figuring it out",
        success: { (response: MyAppResponse!) -> Void in MyAppSettings().authenticatingToken = agent.accessToken
        }) { (response: MyAppResponse!) -> Void in
            var alert = UIAlertController(title: "Oops!", message: "You haven't figured out the token thing!", preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
    }