Explore Library
Code Quiz

Retry Loop Swallows Cancellation

A retry helper keeps hammering the network even after its task is cancelled.

Codeswift
func fetchWithRetry(from url: URL) async throws -> Data {
    var attempt = 0
    while true {
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            return data
        } catch {
            attempt += 1
            if attempt >= 3 { throw error }
            // back off before trying again
            Thread.sleep(forTimeInterval: 1.0)
        }
    }
}

This retry loop is supposed to stop immediately if its Task is cancelled, but it doesn't. What is the bug?