bibin-jaimon / InterviewKit-iOS

5 stars 0 forks source link

How do we convert completion block API to support async await in Swift #8

Open bibin-jaimon opened 9 months ago

bibin-jaimon commented 9 months ago

We can convert old closure based API to async/await using withCheckedContinuation function.

func getName(completion: @escaping (String) -> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now()) {
        completion("Bibin")
    }
}

func getName() async -> String {
    return await withCheckedContinuation { continuation in
        getName { name in
            continuation.resume(with: .success(name))
        }
    }
}

Task {
    do {
        let name = await getName()
        print(name)
    } catch {

    }

}