20

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

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Andrew Ebling
  • 10,175
  • 10
  • 58
  • 75
  • possible duplicate of [How does one make an optional closure in swift?](http://stackoverflow.com/questions/24395853/how-does-one-make-an-optional-closure-in-swift) – Martin R Nov 28 '14 at 09:54
  • Covers same info, but an Objective-C developer may not find that answer (as I didn't) as a result of searching for "block" rather than "closure". Closure is of course correct Swift terminology. – Andrew Ebling Nov 28 '14 at 11:25

3 Answers3

26

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 //
        }
    }
Andrew Ebling
  • 10,175
  • 10
  • 58
  • 75
15

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

Yevhen Dubinin
  • 4,657
  • 3
  • 34
  • 57
1
   typealias ServiceResponse = (AnyObject? , String?) -> Void

   func request(onCompletion: @escaping ServiceResponse){
         stuff you need to write
    }
byJeevan
  • 3,728
  • 3
  • 37
  • 60
Farooque Azam
  • 188
  • 1
  • 10