You need to enable JavaScript to run this app. Swift如何实现条件匹配时依次调用带逃逸闭包的函数并精简代码?
优惠活动
大模型
产品
解决方案
定价
更多

Swift如何实现条件匹配时依次调用带逃逸闭包的函数并精简代码?

方案1:任务队列递归方案(兼容所有iOS版本)

你可以将每个需要执行的单元封装为「判断条件+对应执行函数」的集合,通过递归遍历集合的方式按顺序执行,完全避免嵌套回调:

// 定义执行单元结构体
struct AsyncTask {
    let condition: Bool
    let action: (@escaping () -> Void) -> Void
}

func conditionalCalling() {
    // 按你需要的执行顺序排列任务
    let tasks = [
        AsyncTask(condition: 1 == 1, action: hitFirstAPI),
        AsyncTask(condition: 2 == 2, action: hitSecondAPI),
        AsyncTask(condition: 3 == 3, action: hitThirdAPI)
    ]
    
    // 递归执行任务
    func runTask(at index: Int) {
        guard index < tasks.count else { return }
        let currentTask = tasks[index]
        if currentTask.condition {
            currentTask.action {
                runTask(at: index + 1)
            }
        } else {
            runTask(at: index + 1)
        }
    }
    
    runTask(at: 0)
}

// 原有的API函数无需修改
func hitFirstAPI(done: @escaping ()->Void) {
    // 原有逻辑
    done()
}
func hitSecondAPI(done: @escaping ()->Void) {
    // 原有逻辑
    done()
}
func hitThirdAPI(done: @escaping ()->Void) {
    // 原有逻辑
    done()
}

这个方案的优势是扩展性极强,后续新增/删除执行步骤只需要修改tasks数组即可,无需调整执行逻辑,没有冗余代码。

方案2:Async/Await 简化方案(iOS 13+ / macOS 10.15+ 推荐)

如果你的项目支持Swift Concurrency,可直接将回调式API转为async接口,按顺序写判断逻辑即可,await会自动等待前一个异步任务执行完成再往下走:

// 先将原回调API封装为async版本
func hitFirstAPI() async {
    await withCheckedContinuation { continuation in
        hitFirstAPI(done: continuation.resume)
    }
}

func hitSecondAPI() async {
    await withCheckedContinuation { continuation in
        hitSecondAPI(done: continuation.resume)
    }
}

func hitThirdAPI() async {
    await withCheckedContinuation { continuation in
        hitThirdAPI(done: continuation.resume)
    }
}

// 调用逻辑极度简洁,没有嵌套
func conditionalCalling() {
    Task {
        if 1 == 1 {
            await hitFirstAPI()
        }
        if 2 == 2 {
            await hitSecondAPI()
        }
        if 3 == 3 {
            await hitThirdAPI()
        }
    }
}

内容的提问来源于stack exchange,提问作者Rehan Ali Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 20:21:02