我写了一个带有转义变量的函数
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/