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 :

[code language=”obj-c”]
– (void)yourFunctionName:(NSString *)yourString withCompletionHandler:(void (^)(NSString *yourResult))block;
[/code]

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

[code language=”obj-c”]
func yourFunctionName(parameter:Type, … , withCompletionHandler:(result:Type) -> Void)
[/code]
For more closure syntax : goshdarnclosuresyntax.com

Example

Function Definition:
[code language=”obj-c”]
func closureReturn(isTest:Bool, withCompletionHandler:(result:String) -> Void) {
if(isTest){
withCompletionHandler(result: "Yes")
}
else{
withCompletionHandler(result: "No")
}
}
[/code]
Calling Function:
[code language=”obj-c”]
closureReturn(true) { (result) -> Void in
print(result)
}
[/code]
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 🙂