Skip to content

Instantly share code, notes, and snippets.

@VAndrJ
Created January 20, 2021 18:40
Show Gist options
  • Save VAndrJ/fd2637e79c62f3779b192a67ac470b98 to your computer and use it in GitHub Desktop.
Save VAndrJ/fd2637e79c62f3779b192a67ac470b98 to your computer and use it in GitHub Desktop.
import Foundation
func checkAsync() async -> [String] {
(0...10).map({ "\($0)" })
}
func checkAsyncAwait() async -> [String] {
await checkAsync()
}
@asyncHandler func checkSync() {
print(await checkAsyncAwait())
}
struct CurrencyInfo: Codable {
let ccy: String
let baseCcy: String
let buy: String
let sale: String
}
// ‼ Не повторять в реальной жизни.
// Максимально упрощённый и опасный пример
func fetchCurrencies(completion: @escaping ([CurrencyInfo]) -> Void) {
URLSession.shared.dataTask(with: URL(string: "https://api.privatbank.ua/p24api/pubinfo?exchange&json&coursid=11")!) { data, response, error in
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
completion(try! decoder.decode([CurrencyInfo].self, from: data!))
}
.resume()
}
func checkFetchCurrenciesAsyncAwait() async throws -> [CurrencyInfo] {
return try await withCheckedThrowingContinuation { continuation in
fetchCurrencies { continuation.resume(returning: $0) }
// В случае ошибки continuation.resume(throwing: error)
}
}
runAsyncAndBlock {
do {
print(try await checkFetchCurrenciesAsyncAwait())
} catch {
print(error)
}
print(await checkAsyncAwait())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment