Function with optional completion block in Swift [duplicate]

If you want to default to nil:

func foo(completionBlock: ((String) -> ())? = nil) {

}

If your default completion block is very simple, you can put it right in the function’s definition:

// A default completion block that is simple enough to fit on one line
func foo(completionBlock: (String) -> () = { result in print(result) }) {
    // ...
}

// A default completion block that does nothing
func foo(completionBlock: (String) -> () = {} ) {
    // ...
}

If your default completion block is more complex, you can define it as a separate function:

func defaultCompletion(result: String) {
    // ...
}

func foo(completionBlock: ((String) -> ()) = defaultCompletion) {

}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)