Last active
August 11, 2024 03:34
-
-
Save drewolbrich/cac41538c186ed7fe03d85af1601bacd to your computer and use it in GitHub Desktop.
A replacement for iOS 17 Task/sleep(for: .seconds(_)) that works on iOS 16 and earlier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Task+SleepForSeconds.swift | |
// | |
// Created by Drew Olbrich on 7/12/24. | |
// Copyright © 2024 Lunar Skydiving LLC. All rights reserved. | |
// | |
// MIT License | |
// | |
// Permission is hereby granted, free of charge, to any person obtaining a copy | |
// of this software and associated documentation files (the "Software"), to deal | |
// in the Software without restriction, including without limitation the rights | |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
// copies of the Software, and to permit persons to whom the Software is | |
// furnished to do so, subject to the following conditions: | |
// | |
// The above copyright notice and this permission notice shall be included in all | |
// copies or substantial portions of the Software. | |
// | |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
// SOFTWARE. | |
// | |
import Foundation | |
extension Task where Success == Never, Failure == Never { | |
/// A replacement for iOS 17 `Task/sleep(for: .seconds(_))` that works on iOS 16 and earlier. | |
@available(iOS, deprecated: 17.0, message: "Use Task.sleep(for:) instead") | |
static func sleep(forSeconds duration: TimeInterval) async throws { | |
if #available(iOS 17.0, *) { | |
try await Task.sleep(for: .seconds(duration)) | |
} else { | |
let nanoseconds = UInt64(duration*1_000_000_000) | |
try await Task.sleep(nanoseconds: nanoseconds) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment