Created
November 19, 2021 14:53
-
-
Save berikv/e906834dba9ccc1ce86585b77e0dc68e to your computer and use it in GitHub Desktop.
retry() code block in Swift
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
/// 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