Skip to content

Instantly share code, notes, and snippets.

@yannisalexiou
Created December 19, 2023 14:23
Show Gist options
  • Save yannisalexiou/58e1e4dd2935f0c316f1015d9981e1b3 to your computer and use it in GitHub Desktop.
Save yannisalexiou/58e1e4dd2935f0c316f1015d9981e1b3 to your computer and use it in GitHub Desktop.
A Swift protocol for adding customizable delayed completion to asynchronous operations, supporting generic result types.
protocol DelayedCompletionHandler {
// Define a generic method for delayed completion
func delayedCompletion<T>(
_ result: Result<T, Error>,
_ completion: @escaping (Result<T, Error>) -> Void
)
}
extension DelayedCompletionHandler {
// Generic function with a generic result type
func delayedCompletion<T>(
_ result: Result<T, Error>,
_ completion: @escaping (Result<T, Error>) -> Void
) {
// Generate a random delay between 1 millisecond and 1 second
let delay = Double.random(in: 0.001...1.0)
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
completion(result)
}
}
}
func simpleImplementation(completion: @escaping (Result<String, Error>) -> Void) {
delayedCompletion(.success("Hello World"), completion)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment