Skip to content

Instantly share code, notes, and snippets.

@icanzilb
Created September 9, 2021 09:30
Show Gist options
  • Save icanzilb/04a67c729e5ca82d06ed72b1555ae472 to your computer and use it in GitHub Desktop.
Save icanzilb/04a67c729e5ca82d06ed72b1555ae472 to your computer and use it in GitHub Desktop.
Task.sleep(seconds:)
extension Task where Success == Never, Failure == Never {
/// Suspends the current task for at least the given duration in seconds.
/// Throws if the task is cancelled while suspended.
/// - Parameter seconds: The sleep duration in seconds.
static func sleep(seconds: TimeInterval) async throws {
try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
}
}
@maxhumber
Copy link

maxhumber commented Mar 2, 2022

Awesome! Thanks.

That the default .sleep func throws is confusing to me... so I simplified my implementation to:

extension Task where Success == Never, Failure == Never {
  static func sleep(seconds: TimeInterval) async {
    try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
  }
}

This way I'm able to call without try:

await Task.sleep(seconds: 4)

@icanzilb
Copy link
Author

icanzilb commented Mar 2, 2022

@maxhumber an honest question: why is confusing to you that the function throws?

@maxhumber
Copy link

maxhumber commented Mar 2, 2022

Failure == Never?

Obviously we can just do this:

try? await Task.sleep(nanoseconds: 4_000_000_000)

But the try? is kinda blahhh

@icanzilb
Copy link
Author

icanzilb commented Mar 3, 2022

@maxhumber it's up to you to decide if you want to handle errors or ignore them with try?. If you use try? — you're blocking the mechanism Swift uses to cancel asynchronous tasks, you can read more about it in the documentation in the "Task Cancellation" section https://developer.apple.com/documentation/swift/task#3925721

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment