swift - 不需要闭包返回值时如何调用函数

标签 swift closures

我写了一个带有转义变量的函数

func getData(data: PSData, otherParams: [String], completion: @escaping (Bool) -> Void)

通常我这样调用它

getData(data: myData, otherParams: myOtherParams) { (response) in
    print(response)
}

如果我不需要响应,这样调用函数是否正确?或者有什么可以简化的吗

getData(data: myData, otherParams: myOtherParams) { (_) in }

最佳答案

是的,这是正确的:

getData(data: myData, otherParams: myOtherParams) { _ in }

但是当您传递 nil(不是输入这个丑陋的大括号)或使用 nil 作为默认值时,它会更简洁一些:

func getData(data: PSData, otherParams: [String], completion: ((Bool) -> Void)? = nil)

getData(data: myData, otherParams: myOtherParams, completion: nil)
getData(data: myData, otherParams: myOtherParams) // shorter version

UIKit 使用类似的方式:

@available(iOS 5.0, *)
open func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Swift.Void)? = nil)

关于swift - 不需要闭包返回值时如何调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48583018/

相关文章:

swift - 从主 Storyboard显示 View Controller

python - 为什么设置默认参数值会使该函数成为闭包?

javascript - 在 javascript 闭包中访问变量

ios - 如何制作具有动态类型支持的应用程序?

ios - 如何为 Popover 的箭头添加边框?

ios - 如何解析来自网络请求的错误

javascript - 我知道闭包是什么,但我仍然不明白您为什么(或何时)使用它们

javascript - jQuery 事件处理程序闭包与上下文

C++ COM 对象热修补?

floating-point - 找不到接受提供的参数的 '*' 的重载