I'm trying to compile this simple example, first Xcode 14.3 (Swift 5.8) tells me
No such module 'Concurrency'
Then if I change that line to import _Concurrency, Xcode 14.3 tells me
Cannot find 'withTimeout' in scope
same is true using 'withDeadline()'. What is wrong?
import Foundation
import Concurrency
func fetchImageData() async throws -> Data {
return try await withTimeout(1) {
// Simulate a long-running async operation
let imageData = try await URLSession.shared.data(from: URL(string: "https://example.com/image.jpg")!)
return imageData.0
}
}
There is no need to
importanything for Swift concurrency, as that is imported for you.But there is no
withTimeoutfunction. You could write one, though. Perhaps:Needless to say, I replaced the
TimeInterval(i.e., seconds) with a more generalDurationand made it astaticmethod ofTask, but the overall idea is simple: Basically, start one task for the supplied closure, another for the cancelation of that other task, and whichever finishes first will cancel the other. And obviously, if thewithTimeout, itself, is canceled, then cancel the unstructured concurrency tasks, too.But do not get lost in the weeds of this, as there are probably many variations on the theme one might consider.
Then you could call it like so:
All of that having been said,
URLSession/URLRequestboth already have a timeout parameter, so you might as well use that, perhaps: