将可选块或闭包传递给Swift中的函数

And*_*ing 18 closures swift

将可选块传递给Swift中的函数的正确语法是什么?

And*_*ing 26

虽然不像Objective-C块语法那样难以记住,但它并不明显.notConnected在此示例中,该参数是可选的:

    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 //
        }
    }
Run Code Online (Sandbox Code Playgroud)


Yev*_*nin 13

我找到了它的例子(见下面的链接)并修改它以typealias在我的项目中使用.

斯威夫特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)")
    })
}
Run Code Online (Sandbox Code Playgroud)

来源:Swift中的可选尾部闭包

注意:因为completion声明为可选闭包,它总是会转义.更多内容:可选的非转义闭包