Skip to content

Instantly share code, notes, and snippets.

@Mcrich23
Created November 6, 2025 18:58
Show Gist options
  • Save Mcrich23/8791b977ca1a57e15ed8c546c4f2cfd9 to your computer and use it in GitHub Desktop.
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!
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