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

games202:三,实时环境光照IBL + PRT

面积曲线AUC(area under curve)

小几届的学弟问我,软件测试岗是选11k的华为还是20k的小公司,我直呼受不了,太凡尔赛了~

5G基础学习1、5G网络架构、网络接口及协议栈

Mysql transaction isolation level and MVCC (multi-version concurrency control)

STM32+MPU6050设计便携式Mini桌面时钟(自动调整时间显示方向)

Breaking the Boundary, Huawei's Storage Journey

Challenge LeetCode1000 questions in 365 days - Day 047 Design Circular Queue Circular Queue

MySQL百万数据优化总结 一

受邀出席Rust开发者大会|Rust如何助力量化高频交易?
随机推荐
MySQL百万数据优化总结 一
通过方法引用获取方法名
如何在技术上来保证LED显示屏质量?
当POC遇见RPA:RPA项目顺利实施的关键
MySql模糊查询大全
记录代码
10份重磅报告 — 展望中国数字经济未来
小几届的学弟问我,软件测试岗是选11k的华为还是20k的小公司,我直呼受不了,太凡尔赛了~
Mysql transaction isolation level and MVCC (multi-version concurrency control)
翁恺C语言程序设计网课笔记合集
Oracle 单实例19.11升级到19.12
npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
LayaBox---TypeScript---Module Analysis
Kotlin的协程与生命周期
OSI 七层模型和TCP/IP模型及对应协议(详解)
Event object, do you know it well?
Oracle超全SQL,细节狂魔
Failed to configure mysql, what's going on?
5G基础学习1、5G网络架构、网络接口及协议栈
8大软件供应链攻击事件概述