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

时间:2014-11-28 09:50:45

标签: swift closures

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

3 个答案:

答案 0 :(得分:24)

尽管不像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 //
        }
    }

答案 1 :(得分:12)

我找到了它的示例(请参阅下面的链接)并将其修改为在我的项目中使用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)")
    })
}

来源:Optional trailing closures in Swift

注意:因为completion被声明为可选闭包,所以它总是转义。更多相关内容:Optional Non-Escaping Closures

答案 2 :(得分:0)

typealias ServiceResponse =(AnyObject?,String?)->无效

功能请求(onCompletion:@转义ServiceResponse){          你需要写的东西     }