Skip to content

Continuations

ShenYj edited this page Mar 31, 2022 · 1 revision

Continuations

简介

Swift 5.5 关键字: async/await 这篇笔记中初次在 Swift 上体验了一下 async/await,在新老 api 适配上产生了一点疑问,对此苹果也考虑到了,通过苹果提供的 Continuation函数 帮助我们将原有回调异步函数转换为回调异步 async函数

示例

  • 原有异步回调函数

    func fetchLatestNews(completion: @escaping ([String]) -> Void) {
        DispatchQueue.main.async {
            completion(["Swift 5.5 release", "Apple acquires Apollo"])
        }
    }
  • 使用 Continuations 函数转换为 async 函数

    func fetchLatestNews() async -> [String] {
        await withCheckedContinuation { continuation in
            fetchLatestNews { items in
                continuation.resume(returning: items)
            }
        }
    }
    • resume(returning:) 函数返回,你异步要返回的数据。 只允许调用一次

参考资料

Getting Started

Social

Clone this wiki locally