This means we need to pass a callback function as an argument to greet() function when calling it. The greet() function calls the completion handler right after it has printed “Hello world!” into the console. This executes the completion handler we pass into the greet() function call.
As an example, many functions that start an asynchronous operation take a closure argument as a completion handler. The function returns after it starts the operation, but the closure isn't called until the operation is completed—the closure needs to escape, to be called later.
Swift Closures with Completion handler Closures are self-contained blocks of functionality that can be passed around and used in your code. Said differently, a closure is a block of code that you can assign to a variable. You can then pass it around in your code, for instance to another function. …
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.
Say you have a download function to download a file from network, and want to be notified when download task has finished.
typealias CompletionHandler = (success:Bool) -> Void
func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {
// download code.
let flag = true // true if download succeed,false otherwise
completionHandler(success: flag)
}
// How to use it.
downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in
// When download completes,control flow goes here.
if success {
// download success
} else {
// download fail
}
})
Hope it helps.
I had trouble understanding the answers so I'm assuming any other beginner like myself might have the same problem as me.
My solution does the same as the top answer but hopefully a little more clear and easy to understand for beginners or people just having trouble understanding in general.
To create a function with a completion handler
func yourFunctionName(finished: () -> Void) {
print("Doing something!")
finished()
}
to use the function
override func viewDidLoad() {
yourFunctionName {
//do something here after running your function
print("Tada!!!!")
}
}
Your output will be
Doing something
Tada!!!
Hope this helps!
Simple Example:
func method(arg: Bool, completion: (Bool) -> ()) {
print("First line of code executed")
// do stuff here to determine what you want to "send back".
// we are just sending the Boolean value that was sent in "back"
completion(arg)
}
How to use it:
method(arg: true, completion: { (success) -> Void in
print("Second line of code executed")
if success { // this will be equal to whatever value is set in this method call
print("true")
} else {
print("false")
}
})
Swift 5.0 + , Simple and Short
example:
Style 1
func methodName(completionBlock: () -> Void) {
print("block_Completion")
completionBlock()
}
Style 2
func methodName(completionBlock: () -> ()) {
print("block_Completion")
completionBlock()
}
Use:
override func viewDidLoad() {
super.viewDidLoad()
methodName {
print("Doing something after Block_Completion!!")
}
}
Output
block_Completion
Doing something after Block_Completion!!
We can use Closures for this purpose. Try the following
func loadHealthCareList(completionClosure: (indexes: NSMutableArray)-> ()) {
//some code here
completionClosure(indexes: list)
}
At some point we can call this function as given below.
healthIndexManager.loadHealthCareList { (indexes) -> () in
print(indexes)
}
Please refer the following link for more information regarding Closures.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
In addition to above : Trailing closure can be used .
downloadFileFromURL(NSURL(string: "url_str")!) { (success) -> Void in
// When download completes,control flow goes here.
if success {
// download success
} else {
// download fail
}
}
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