Created
December 19, 2023 14:23
-
-
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.
This file contains 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
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