swift - 将可选 block 或闭包传递给 Swift 中的函数

标签 swift closures

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

最佳答案

虽然不像 Objective-C block 语法那样难记,但它远非显而易见。 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 //
        }
    }

关于swift - 将可选 block 或闭包传递给 Swift 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27185941/

相关文章:

php - 调用闭包时的奇怪行为

java - 在 Java 中引用匿名内部类中封闭类的非最终字段

ios - 当 ARC 在 iOS 中出现时,我们是否还需要使用 xcode 工具(Allocations 和 Leak)?

ios - 关闭位置和通知设置 Xcode Ui 测试

swift - 为什么我们在 Swift 变量声明中使用关键字 "get"?

swift - 添加新枚举值时的切换行为

rust - Blanket impl、HRTB 和 "impl"抽象返回类型 : "expected bound lifetime parameter"

swift - Swift中的 optional 值是什么?

swift - 如何仅在执行另一个代码块后才执行一个代码块

rust - 不可变值仍在移动