Use of Blocks(Closures) or Completion Handlers with Function in Swift — iOS
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("Yes")
}
else{
withCompletionHandler("No")
}
}
Calling Function:
closureReturn(isTest: true, withCompletionHandler: { (result) 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?
Originally published at ashishkakkad.com on February 28, 2016.