Skip to content

Instantly share code, notes, and snippets.

@gotev
Last active December 4, 2022 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gotev/c80813efa1b82c507bddef08d9fe72eb to your computer and use it in GitHub Desktop.
Save gotev/c80813efa1b82c507bddef08d9fe72eb to your computer and use it in GitHub Desktop.
Swift Multiplatform Experiments. Read comments below.
import Foundation
// needed for Linux
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
// New async await URLSession extensions are available solely on Apple platform
// so this polyfill it's necessary, otherwise the code does not compile on Linux
extension URLSession {
func universalData(for request: URLRequest) async throws -> (Data, URLResponse?) {
#if canImport(FoundationNetworking)
print("On Linux")
return await withCheckedContinuation { continuation in
URLSession.shared.dataTask(with: request) { data, response, _ in
guard let data = data else {
fatalError()
}
continuation.resume(returning: (data, response))
}.resume()
}
#else
print("On macOS")
return try await URLSession.shared.data(for: request)
#endif
}
}
struct Dog: Codable {
let message: String
let status: String
var url: URL { URL(string: message)! }
}
func fetchDog() async throws -> Dog {
let dogURL = URL(string: "https://dog.ceo/api/breeds/image/random")!
let request = URLRequest(url: dogURL)
let (data, _) = try await URLSession.shared.universalData(for: request)
return try JSONDecoder().decode(Dog.self, from: data)
}
do {
print(try await fetchDog())
} catch {
print(error)
print("ouch")
}
@gotev
Copy link
Author

gotev commented Dec 4, 2022

It runs successfully on:

  • Intel Core i9 MacBookPro running macOS Ventura 13.0.1 and Xcode 14.1.0
  • Raspberry Pi 2 running Raspbian Bullseye 11 and Swift built for ARM installed with (select the first option, to get latest available swift):
    curl -s https://archive.swiftlang.xyz/install.sh | sudo bash
    sudo apt install swiftlang
    

Useful Article about Swift Concurrency on Linux

raspberry

macOS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment