如何设计一个通用的重试机制,接受任意异步函数和重试次数?
解读
国内 iOS 面试中,这道题高频出现在“网络层封装”或“基础组件设计”环节,考察点集中在:
- 对 Swift 并发模型(async/throwing)的理解深度;
- 泛型与高阶函数的组合能力;
- 对“失败策略”与“取消策略”的边界处理;
- 是否具备工程级可维护性(日志、回调、测试注入)。
面试官通常会在你给出初版后继续追问:
- 如果重试间隔要指数退火怎么办?
- 如何支持“只针对特定错误重试”?
- 怎样在 SwiftUI 中无痛接入?
因此,答案必须一次到位:接口简洁、实现解耦、策略可插拔,同时兼顾性能(无 GCD 泄漏、无 Task 悬挂)。
知识点
- rethrows 与 async 泛型闭包:保证调用方零成本抽象。
- 结构化并发:Task、TaskGroup、withTaskCancellationHandler。
- Clock/ContinuousClock:iOS 16+ 官方休眠 API,替代旧的 sleep(&)。
- 有界退火算法:maxDelay 封顶,防止雪崩。
- 错误过滤器:Swift 错误为值类型,可用泛型 + where 子句做编译期约束。
- 取消响应:withTaskCancellationHandler 在每次重试前检查 Task.isCancelled。
- 日志注入:@autoclosure 延迟构造日志字符串,Release 下自动抹除。
- 单测友好:把“退火策略”与“重试引擎”拆成两个协议,方便 mock 时间源。
答案
import Foundation
/// 1. 退火策略协议
public protocol BackoffStrategy: Sendable {
/// 返回下一次等待间隔,单位秒
func next(after attempt: Int) -> Duration
}
/// 2. 线性退火(默认)
public struct LinearBackoff: BackoffStrategy {
public let base: Duration
public init(base: Duration = .seconds(1)) { self.base = base }
public func next(after attempt: Int) -> Duration { base }
}
/// 3. 指数退火 + 封顶
public struct ExponentialBackoff: BackoffStrategy {
public let initial: Duration
public let max: Duration
public let multiplier: Double
public init(initial: Duration = .milliseconds(200),
max: Duration = .seconds(30),
multiplier: Double = 2) {
self.initial = initial; self.max = max; self.multiplier = multiplier
}
public func next(after attempt: Int) -> Duration {
let pow = Duration.seconds(initial.components.seconds * multiplier.pow(Double(attempt - 1)))
return min(pow, max)
}
}
/// 4. 错误过滤器
public struct RetryPolicy<E: Error & Equatable>: Sendable {
public let shouldRetry: (E) -> Bool
public init(shouldRetry: @escaping (E) -> Bool) {
self.shouldRetry = shouldRetry
}
/// 预置:只重试网络超时
public static let urlTimeout: RetryPolicy<URLError> = .init { error in
error.code == .timedOut || error.code == .networkConnectionLost
}
}
/// 5. 重试引擎
public enum Retry {
/// 通用异步重试
/// - Parameters:
/// - maxAttempts: 总尝试次数,必须 >= 1
/// - backoff: 退火策略
/// - policy: 可选的错误过滤器;nil 表示所有 Error 都重试
/// - operation: 异步 throwing 闭包
/// - Returns: 首次成功值
/// - Throws: 最后一次失败错误(若中途取消则抛出 CancellationError)
public static func execute<T, E: Error & Equatable>(
maxAttempts: Int = 3,
backoff: some BackoffStrategy = LinearBackoff(),
policy: RetryPolicy<E>? = nil,
operation: @escaping () async throws -> T
) async throws -> T {
precondition(maxAttempts >= 1, "maxAttempts 必须 >= 1")
var lastError: Error?
for attempt in 1...maxAttempts {
do {
return try await operation()
} catch {
lastError = error
// 取消检查
try Task.checkCancellation()
// 错误过滤
if let typed = error as? E, let policy = policy, !policy.shouldRetry(typed) {
throw error
}
// 最后一次不再睡
if attempt < maxAttempts {
let delay = backoff.next(after: attempt)
try await Task.sleep(for: delay)
}
}
}
throw lastError!
}
}
使用示例:
// 网络请求
let data = try await Retry.execute(maxAttempts: 5,
backoff: ExponentialBackoff(),
policy: RetryPolicy.urlTimeout) {
try await URLSession.shared.data(from: url).0
}
// SwiftUI 生命周期内自动取消
Task {
do {
let image = try await Retry.execute {
try await fetchImage(id: 1)
}
self.image = image
} catch is CancellationError {
// 用户退出页面,无需提示
} catch {
self.errorMessage = error.localizedDescription
}
}
拓展思考
- 退火策略再进化:引入“全抖动”(full jitter) 打散重试风暴,适合高并发网关场景。
- 重试与幂等:面试里可主动提及“业务接口是否幂等”,体现你对后端语义的敏感。
- 与 Combine 共存:若老项目仍用 Combine,可封装
retry(when:maxAttempts:)操作符,内部桥接上述 Retry 引擎,保证代码单事实来源。 - 可观测性:接入 os_log 子系统,记录 attempt、elapsed、errorCode,方便线上灰度时快速定位“重试放大”导致的 5xx 飙升。
- 编译期重试次数:利用 Swift 5.9 的宏功能,提供
@Retry(maxAttempts: 3)属性宏,直接生成包裹代码,减少手写模板。