如何在SWIFT中实现Objective-C回调处理程序? [英] How to implement Objective-C callback handler in SWIFT?

查看:183
本文介绍了如何在SWIFT中实现Objective-C回调处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标c代码如下所示:

   - (void)signInAccountWithUserName:(NSString *)userName 
密码:(NSString *)密码
completion:(void(^)(BOOL success))completionBlock
{
//使用`userName`和`password`
// BOOL loginSuccessful = [LoginManager contrivedLoginMethod];

//注意,我们将BOOL传递回完成块。
if(completionBlock!= nil)completionBlock(loginSuccessful);
}

,此方法的用法是:

  [self signInAccountWithUserName:@Bob
password:@BobsPassword
completion:^(BOOL success){
if成功){
[self displayBalance];
} else {
//无法登录。向用户显示警报。
}
}];

如何在Swift中实现它?

$

  func signInAccount(用户名:NSString !,密码: NSString !, completionBlock:((Bool) - >())?){
if completionBlock {
completionBlock!(true)
}
}

signInAccount(Bob,BobPassword){
(var success)in
println(\(success))
};

signInAccount(Bob,BobPassword,nil)


The objective c code seems like this:

- (void)signInAccountWithUserName:(NSString *)userName
                         password:(NSString *)password
                       completion:(void (^)(BOOL success))completionBlock
{
    // Log into the account with `userName` and `password`...
    // BOOL loginSuccessful = [LoginManager contrivedLoginMethod];

    // Notice that we are passing a BOOL back to the completion block.
    if (completionBlock != nil) completionBlock(loginSuccessful);
}

and this method usage is:

[self signInAccountWithUserName:@"Bob"
                       password:@"BobsPassword"
                     completion:^(BOOL success) {
                         if (success) {
                             [self displayBalance];
                         } else {
                             // Could not log in. Display alert to user.
                         }
                     }];

How can I implement it in Swift? What is the equivalent implementation?

解决方案

func signInAccount(username:NSString!, password:NSString!, completionBlock:((Bool)->())?) {
    if completionBlock {
        completionBlock!(true)
    }
}

signInAccount("Bob", "BobPassword") {
    (var success) in
    println("\(success)")
};

signInAccount("Bob", "BobPassword", nil)

这篇关于如何在SWIFT中实现Objective-C回调处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆