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!");
}
@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.
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.
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.
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.
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!");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With