Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a block with arguments in swift?

Having a hard time figuring out how to properly declare/use blocks with swift. What would be the swift equivalent of the following code?

Thanks.

^(PFUser *user, NSError *error) {
if (!user) {
    NSLog(@"Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew) {
    NSLog(@"User signed up and logged in through Facebook!");
} else {
    NSLog(@"User logged in through Facebook!");
}
like image 474
Brandon Foo Avatar asked Jun 03 '14 23:06

Brandon Foo


People also ask

What is@ autoclosure in Swift?

@autoclosure in Swift is a type of closure that allows to omit braces and make it look like a normal expression. Under the hood, however, it's still a closure. By understanding what this means, we can improve the efficiency of our code.

What are the blocks in Swift?

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

How do you pass a function as a parameter in Swift?

To pass function as parameter to another function in Swift, declare the parameter to receive a function with specific parameters and return type. The syntax to declare the parameter that can accept a function is same as that of declaring a variable to store a function.

When to use closure in Swift?

Functions and closures are first-class objects in Swift: you can store them, pass them as arguments to functions, and treat them as you would any other value or object. Passing closures as completion handlers is a common pattern in many APIs. Standard Swift library uses closures mostly for event handling and callbacks.


1 Answers

The equivalent of Objective-C blocks are swift closures, so it would go as follows

{ (user: PFUser, error: NSError) in
  if (!user) {
    println("Uh oh. The user cancelled the Facebook login.");
  } else if (user.isNew) {
    println("User signed up and logged in through Facebook!");
  } else {
    println("User logged in through Facebook!");
  }
}
like image 172
Gabriele Petronella Avatar answered Sep 29 '22 16:09

Gabriele Petronella