当前位置:网站首页>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??
感谢观赏,再会了!
边栏推荐
猜你喜欢

OSI 七层模型和TCP/IP模型及对应协议(详解)

雷克萨斯,锁死的安全,挡不住的心寒

365天挑战LeetCode1000题——Day 047 设计循环队列 循环队列

sva 断言资料

Camera Hal OEM模块 ---- cmr_snapshot.c

jacoco的学习以及理解

智能手表前景如何?
[email protected] This version of tar is no longer supported, and will not receive"/>npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive

ssm web page access database data error
开箱即用-使用异步加载布局来优化页面启动速度的几种方案
随机推荐
FinClip | 来了, 2022 年 7 月更新大盘点
Excel动态图制作
华为eNSP(基础实验通信)
The exchange - string dp
图形处理单元(GPU)的演进
LayaBox---TypeScript---Advanced Type
阿里云数据存储生态计划发布,助力伙伴数据创新
突破边界,华为存储的破壁之旅
从零开始Blazor Server(5)--权限验证
大疆P4M云遮挡矫正
深度学习100例 —— 卷积神经网络(CNN)实现mnist手写数字识别
npm WARN config global `--global`, `--local` are deprecated. Use `--location解决方案
LayaBox---TypeScript---Mixins
Oracle 单实例19.11升级到19.12
Event object, do you know it well?
ASP.NET Core 6框架揭秘实例演示[31]:路由&quot;高阶&quot;用法
5G网络切片技术
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一
idea常用插件
3年测试在职,月薪还不足2w,最近被裁员,用亲身经历给大家提个醒...