Skip to content

Instantly share code, notes, and snippets.

@berikv
Created November 19, 2021 14:53
Show Gist options
  • Save berikv/e906834dba9ccc1ce86585b77e0dc68e to your computer and use it in GitHub Desktop.
Save berikv/e906834dba9ccc1ce86585b77e0dc68e to your computer and use it in GitHub Desktop.
retry() code block in Swift
/// Retry a block of code until it succeeds, maximum n times
///
/// Usage:
/// ```
/// var failTimes = 3
/// try retry(5) {
/// if failTimes > 0 {
/// failTimes -= 1
/// throw MyError()
/// }
/// print("Success!")
/// }
/// struct MyError: Error {}
/// ```
func retry<R>(_ count: Int, block: () throws -> R) rethrows -> R {
var attempt = 0
while true {
do { return try block() }
catch {
if attempt == count { throw error }
attempt += 1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment