Reputation: 1146
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?
Upvotes: 3
Views: 4360
Reputation: 902
func signInAccount(username:NSString!, password:NSString!, completionBlock:((Bool)->())?) {
if completionBlock {
completionBlock!(true)
}
}
signInAccount("Bob", "BobPassword") {
(var success) in
println("\(success)")
};
signInAccount("Bob", "BobPassword", nil)
Upvotes: 4
Reputation: 21144
This is how you would implement methods with callbacks in 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")
}
})
Upvotes: 0