当前位置:网站首页>When not to use () instead of Void in Swift
When not to use () instead of Void in Swift
2022-08-02 11:19:00 【Giant panda Hou Pei】
概述
这是一篇很短的文章.
我们知道,在Swift中 () 和 Void can be used interchangeably in some cases,它们都表示“空”类型.注意该“空”类型和nilTypes are not the same thing,后者其实是Optional的一种,The former means“没有任何值”.
比如,我们可以这样写:
func test(_ handler: () -> Void){
handler()
}
也可以这样写:
func test(_ handler: () -> ()){
handler()
}
它们都表示handler闭包返回“空”值,即不返回任何值.
那么,在什么情况下不能用()表示Void呢?
One case is:when we need to pass“空”类型本身,而不是“空”Types represent value.
什么意思?
下面举个栗子
一个栗子
let start = Date.timeIntervalSinceReferenceDate
// It needs to be clear that the type returned by our task group is“空”类型本身,而不是“空”the value corresponding to the type
await withThrowingTaskGroup(of: Void.self, body: {
for _ in 0 ..< 100 {
$0.addTask {
try await Task.sleep(nanoseconds: 1_000_000_000)
}
}
})
let end = Date.timeIntervalSinceReferenceDate
print(String(format: "Duration: %.2fs", end-start))
如上所示,异步函数withThrowingTaskGroupThe first parameter that needs to be passed is“空”类型本身,rather than its corresponding value,所以我们需要用 Void.self 而不是 Void 来填充.
但是,这里不可以使用() ,即:
await withThrowingTaskGroup(of: ().self, body: {
for _ in 0 ..< 100 {
$0.addTask {
try await Task.sleep(nanoseconds: 1_000_000_000)
}
}
})
这会导致编译失败:
总结
via this little chestnut,我们学习了 () 和 Void Scenarios that can and cannot be replaced with each other,Did you guys learn??
感谢观赏,再会了!
边栏推荐
- Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition
- Camera Hal OEM模块 ---- cmr_snapshot.c
- 当POC遇见RPA:RPA项目顺利实施的关键
- LeetCode笔记:Weekly Contest 304
- Breaking the Boundary, Huawei's Storage Journey
- 您应该知道的 Google Sheets 使用技巧
- leetcode: 200. 岛屿数量
- find查找多类型结尾文件
- Question about #oracle#, how to solve it?
- SQLAlchemy使用教程
猜你喜欢
随机推荐
配置mysql失败了,这是怎么回事呢?
C#为listview选中的项添加右键菜单
通过方法引用获取方法名
C#/VB.NET to add more lines more columns image watermark into the Word document
爆款视频怎么做?这里或许有答案!
Outsourced Student Management System Architecture Documentation
腾讯云云函数SCF—入门须知
MSYS2 QtCreator Clangd code analysis can not find mm_malloc.h problem remedy
博云入选Gartner中国DevOps代表厂商
Multithreading (Basic) - 40,000 word summary
【2022 小目标检测综述】Towards Large-Scale Small Object Detection: Survey and Benchmarks
Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition
Three.JS程序化建模入门
QT笔记——在一个窗口上显示另外一个透明窗口
org.apache.ibatis.binding.BindingException Invalidbound statement (not found)的解决方案和造成原因分析(超详细)
SQL(面试实战07)
bgp与mpls综合实验
开箱即用-使用异步加载布局来优化页面启动速度的几种方案
您应该知道的 Google Sheets 使用技巧
基于threejs的商品VR展示平台的设计与实现思路