Use of Blocks(Closures) or Completion Handlers with Function in Swift – iOS

Blocks in Objective-C

In Objective-C we are using the blocks(completion handlers) with functions as follows :

- (void)yourFunctionName:(NSString *)yourString withCompletionHandler:(void (^)(NSString *yourResult))block;

Closures 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.

Syntax with Function

func yourFunctionName(parameter:Type, ... , withCompletionHandler:(result:Type) -> Void)

For more closure syntax : goshdarnclosuresyntax.com

Example

Function Definition:

func closureReturn(isTest:Bool, withCompletionHandler:(result:String) -> Void) {
    if(isTest){
        withCompletionHandler(result: "Yes")
    }
    else{
        withCompletionHandler(result: "No")
    }
}

Calling Function:

closureReturn(true) { (result) -> Void in
    print(result)
}

Output should be respective to value true/false.


In next post I will write a tutorial on a wrapper class for Alamofire with use of SwiftyJSON by using closures.

It will be related to this post How to use Alamofire and SwiftyJSON with Swift? – Swift 2 – iOS 9 – Xcode 7

Happy Coding 🙂