Created
November 6, 2025 18:58
-
-
Save Mcrich23/8791b977ca1a57e15ed8c546c4f2cfd9 to your computer and use it in GitHub Desktop.
Ever wanted to run a SwiftUI animation in an asynchronous context? Here is a function to do it!
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
| import SwiftUI | |
| public func withAnimation<Result>( | |
| _ animation: Animation? = .default, | |
| _ body: @MainActor @escaping () throws -> Result | |
| ) async rethrows { | |
| await withCheckedContinuation { continuation in | |
| // Ensure the work runs on the MainActor | |
| Task { @MainActor in | |
| do { | |
| // SwiftUI's withAnimation is synchronous and runs on main thread | |
| let _ = try SwiftUI.withAnimation(animation) { | |
| try body() | |
| } completion: { | |
| continuation.resume() | |
| } | |
| } catch { | |
| print("Animation Error: \(error)") | |
| continuation.resume() | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment