Created
November 19, 2021 14:53
-
-
Save berikv/e906834dba9ccc1ce86585b77e0dc68e to your computer and use it in GitHub Desktop.
Revisions
-
berikv created this gist
Nov 19, 2021 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,24 @@ /// 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 } } }