将可选块或闭包传递给Swift中的函数 [英] Pass optional block or closure to a function in Swift

查看:100
本文介绍了将可选块或闭包传递给Swift中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

作为Objective-C块语法,它远不是显而易见的。在此示例中, notConnected 参数是可选的:

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 //
        }
    }

这篇关于将可选块或闭包传递给Swift中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆