Swift retry helper with capped exponential backoff
Swift
import Foundation
func retry<T>(attempts: Int = 4, base: TimeInterval = 0.2,
operation: () throws -> T) throws -> T {
var delay = base
var lastError: Error?
for attempt in 0..<attempts {
do { return try operation() }
catch {
lastError = error
if attempt < attempts - 1 {
let jitter = Double.random(in: 0...delay)
Thread.sleep(forTimeInterval: min(delay + jitter, 5))
}
delay = min(delay * 2, 5)
}
}
throw lastError ?? CancellationError()
}