如何使用新的 Swift 5.5
await
关键字来等待一段时间?
DispatchQueue
的 asyncAfter(deadline:execute:)
: 获得类似的结果
func someLongTask(completion: @escaping (Int) -> Void) {
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
completion(Int.random(in: 1 ... 6))
}
}
someLongTask { diceRoll in
print(diceRoll)
}
如何在 Swift 5.5 中将其转换为使用
async
& await
?
sleep(until:tolerance:clock:)
,使用方式如下:
// 3 seconds
try await Task.sleep(until: .now + .seconds(3))
Task.sleep(nanoseconds:)
等待特定的时间。这是以纳秒而不是秒来衡量的。
这是一个例子:
func someLongTask() async -> Int {
try? await Task.sleep(nanoseconds: 1 * 1_000_000_000) // 1 second
return Int.random(in: 1 ... 6)
}
Task {
let diceRoll = await someLongTask()
print(diceRoll)
}
使用睡眠扩展可能会更容易,这样您就可以在几秒钟内通过:
extension Task where Success == Never, Failure == Never {
static func sleep(seconds: Double) async throws {
let duration = UInt64(seconds * 1_000_000_000)
try await Task.sleep(nanoseconds: duration)
}
}
现在这样称呼:
try await Task.sleep(seconds: 1)
请注意,睡眠是通过
try
调用的。如果睡眠被取消,则会引发错误。如果你不在乎是否取消,只需try?
就可以了。
从 iOS 16 开始,您可以直接使用
.seconds
,如下所示:
try await Task.sleep(for: .seconds(10))