当前位置:网站首页>Swift中什么时候不能用 () 代替 Void 来使用
Swift中什么时候不能用 () 代替 Void 来使用
2022-08-02 11:15:00 【大熊猫侯佩】
概述
这是一篇很短的文章。
我们知道,在Swift中 () 和 Void 在一些场合下是可以互为替代的,它们都表示“空”类型。注意该“空”类型和nil类型不是一回事,后者其实是Optional的一种,而前者表示“没有任何值”。
比如,我们可以这样写:
func test(_ handler: () -> Void){
handler()
}
也可以这样写:
func test(_ handler: () -> ()){
handler()
}
它们都表示handler闭包返回“空”值,即不返回任何值。
那么,在什么情况下不能用()表示Void呢?
一种场合是:当我们需要传递“空”类型本身,而不是“空”类型表示值的时候。
什么意思?
下面举个栗子
一个栗子
let start = Date.timeIntervalSinceReferenceDate
// 需要明确我们的任务组返回的类型为“空”类型本身,而不是“空”类型对应的值
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))
如上所示,异步函数withThrowingTaskGroup的第一个参数需要传递的是“空”类型本身,而不是它所对应的值,所以我们需要用 Void.self 而不是 Void 来填充。
但是,这里不可以使用() ,即:
await withThrowingTaskGroup(of: ().self, body: {
for _ in 0 ..< 100 {
$0.addTask {
try await Task.sleep(nanoseconds: 1_000_000_000)
}
}
})
这会导致编译失败:
总结
通过这个小栗子,我们学习了 () 和 Void 可以和不可以相互替代的场景,小伙伴学会了吗?
感谢观赏,再会了!
边栏推荐
猜你喜欢
随机推荐
从众多接口中脱颖而出的最稳定的接口——淘宝详情api
What is the future of smartwatches?
Failed to configure mysql, what's going on?
Question about #oracle#, how to solve it?
Nanny Level Tutorial: Write Your Own Mobile Apps and Mini Programs (Part 2)
Kotlin的协程与生命周期
如何在技术上来保证LED显示屏质量?
LeetCode每日一练 —— 225. 用队列实现栈
Mysql transaction isolation level and MVCC (multi-version concurrency control)
LayaBox---TypeScript---Module
放苹果(暑假每日一题 13)
循环结构--do-while循环
C#/VB.NET to add more lines more columns image watermark into the Word document
Challenge LeetCode1000 questions in 365 days - Day 047 Design Circular Queue Circular Queue
同样做软件测试,和月收入 3W 的学弟聊了一晚上,我彻底崩溃了
Geoffery Hinton: The Next Big Thing in Deep Learning
365天挑战LeetCode1000题——Day 047 设计循环队列 循环队列
打破千篇一律,DIY属于自己独一无二的商城
MySQL百万数据优化总结 一
学习笔记-支付宝支付