如何使用异步等待 Swift 5.5 等待 x 秒

问题描述 投票:0回答:2

如何使用新的 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

swift concurrency swift5 swift-concurrency
2个回答
60
投票

iOS 16+ / macOS 13+

有一个较新的 API,

sleep(until:tolerance:clock:)
,使用方式如下:

// 3 seconds
try await Task.sleep(until: .now + .seconds(3))

iOS <16 / macOS <13

您可以使用

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?
就可以了。


15
投票

从 iOS 16 开始,您可以直接使用

.seconds
,如下所示:

try await Task.sleep(for: .seconds(10))
© www.soinside.com 2019 - 2024. All rights reserved.