What is the correct syntax to pass an optional block to a function in Swift?
You should enclose the optional closure in parentheses. This will properly scope the ? operator. func then(onFulfilled: ()->(), onReject: (()->())?){ if let callableRjector = onReject { // do stuff! } }
Difference between Function and ClosureFunction is declared using func keyword whereas Closure doesn't have func keyword. Function has always name but Closure doesn't have. Function doesn't have in keyword but closure has in the keyword.
In Swift, a closure is a special type of function without the function name. For example, { print("Hello World") } Here, we have created a closure that prints Hello World . Before you learn about closures, make sure to know about Swift Functions.
Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.
Although not as hard to remember as the Objective-C block syntax, it's far from obvious. The notConnected
parameter is optional in this example:
func whenConnected(block: Void -> Void, notConnected: ((Void) -> Void)?, showErrorMessage: Bool) -> Void {
let connected = Reachability.isConnectedToNetwork()
if connected {
block()
} else {
notConnected?()
}
if showErrorMessage {
// your error handling //
}
}
I found the example of it (see link below) and modified it to use typealias
in my project.
Swift 3:
import Foundation
typealias CompletionBlock = (NSError?) -> Void
var completionBlock: CompletionBlock?
// a function declaration w/ optional closure param and default value
func doSomething(completion: CompletionBlock? = nil) {
// assign to the property, to call back out of this function's scope
completionBlock = completion
// ...
// optional closure callback
completionBlock?(nil)
// ...
}
func doSomethingElse() {
// 1. pass optional (nil) closure to a function
doSomething()
// 2. pass optional (non-nil) closure to a function
doSomething(completion: { (error) -> Void in
print("error: \(error)")
})
}
Source: Optional trailing closures in Swift
NOTE: Because the completion
is declared as an optional closure, it always escapes. More on that: Optional Non-Escaping Closures
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