目标c代码如下所示:
- (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);
}
这个方法用法是:
[self signInAccountWithUserName:@"Bob"
password:@"BobsPassword"
completion:^(BOOL success) {
if (success) {
[self displayBalance];
} else {
// Could not log in. Display alert to user.
}
}];
如何在Swift中实现它?什么是等效实现?
答案 0 :(得分:4)
func signInAccount(username:NSString!, password:NSString!, completionBlock:((Bool)->())?) {
if completionBlock {
completionBlock!(true)
}
}
signInAccount("Bob", "BobPassword") {
(var success) in
println("\(success)")
};
signInAccount("Bob", "BobPassword", nil)
答案 1 :(得分:0)
这是你在swift中使用回调实现方法的方法。
func signInAccountWithUsername(userName:String!, password: String!, completion: (Bool) -> Void){
completion(false)
}
signInAccountWithUsername("Swift", "secret swift", {
success in
if success{
println("Success")
}else{
println("Failure")
}
})