Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass optional block or closure to a function in Swift

Tags:

What is the correct syntax to pass an optional block to a function in Swift?

like image 425
Andrew Ebling Avatar asked Nov 28 '14 09:11

Andrew Ebling


People also ask

How do you declare a optional closure 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! } }

What is the difference between closure and function in Swift?

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.

What is closure in function and create it in Swift?

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.

Why do we need closure in Swift?

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.


2 Answers

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 //
        }
    }
like image 56
Andrew Ebling Avatar answered Sep 21 '22 15:09

Andrew Ebling


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

like image 25
Yevhen Dubinin Avatar answered Sep 18 '22 15:09

Yevhen Dubinin