ios - 如何选择性地将值传递给 Swift 中的闭包?

标签 ios xcode swift syntax

我有以下函数,它读取一些心率数据并接受闭包形式的回调,例如:

func readHeartRate(callback: ((samples: [HKQuantitySample]?, average: Double?, error: NSError!) -> Void)!){
   // ...
   // ERROR - call the callback with no samples or average
   callback(samples: nil, average: nil, error: error)
})

现在,我将 samplesaveragenil 显式传回回调。

但是,由于 sampleserror 是可选的,并且由于我在闭包中明确声明了名称,所以我认为这是可能的,而不是:

callback(error: error)

但是,当我这样做时,xcode 会提示并抛出错误:

Missing argument for parameter 'samples' in call

有没有一种方法可以只使用必要的值来调用回调以避免使我的代码困惑?

最佳答案

来自 The Swift Programming Language :

Closure expression syntax can use constant parameters, variable parameters, and inout parameters. Default values cannot be provided. Variadic parameters can be used if you name the variadic parameter and place it last in the parameter list.

因此,能够使用可变数量的指定参数调用闭包的唯一方法是使用可变参数,我认为这不是您想要的。

关于ios - 如何选择性地将值传递给 Swift 中的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29279038/

相关文章:

ios - 解包可选值时意外发现 nil [swift 3.0]

ios - 如何让 UIButton 在按下时缩小为 UIActivityIndi​​cator?

ios - 如何在 Xcode 的检查器中编辑自定义类属性?

ios - 导入 header 两次: duplicate symbol for architecture x86_64

swift - Xcode 8.1 Swift 3 错误 : cannot convert value of type 'String' to expected argument type 'UnsafeMutableRawPointer'

ios - 我们可以使用 Pencil Kit 在照片标记中添加文本、形状和签名吗?

ios - 如何在 Swift 中以编程方式设置 UITableView 单元格高度?

swift - 如何通过单击下一步按钮添加和查看数组中下一张图像的图像

multithreading - 如何在不同线程上运行函数?

objective-c - 可达性模块