Skip to content

Instantly share code, notes, and snippets.

@berikv
Created November 19, 2021 14:53
Show Gist options
  • Select an option

  • Save berikv/e906834dba9ccc1ce86585b77e0dc68e to your computer and use it in GitHub Desktop.

Select an option

Save berikv/e906834dba9ccc1ce86585b77e0dc68e to your computer and use it in GitHub Desktop.

Revisions

  1. berikv created this gist Nov 19, 2021.
    24 changes: 24 additions & 0 deletions Retry.swift
    Original 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
    }
    }
    }