Is there a guarantee that the trailing closure to Future.init()
is run right away? And if there is, why is the closure marked escaping?
This is condensed from a more complicated example, but the question is, is this safe to do?
var task: URLSessionUploadTask!
let future = Future<Data, Error> { promise in
task = self.uploadTask(with: urlRequest, fromFile: fileURL) {
data, response, error in
// shove result/error into the promise here
}
}
// Q: do we know task was created before we reach this point? Or must I
// move the following line up inside the trailing closure to ensure the
// correct order of execution?
task.resume()
If the trailing closure to Future.init() is run before returning, then task
will have been assigned to, and I can call its resume function outside the closure. If not, I must call task.resume()
inside the trailing closure to Future.
Which is it? Everything I have read indicates that Futures do NOT wait for someone to subscribe, and run their trailing closure right away. But given that the API marks the trailing closure as escaping, I'm worried that there's no contractual guarantee this is true.