How to mark a closure nonisolated?

I have code like this (which I also believe is quite common):

Network().fetchResource { response in
  // Process response
}

Network is implemented in ObjC:

- (void)fetchResource:(void(^)(NSData *))completion {
  // Simplified code to demo
  dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
    completion(data);
  })
}

When the Swift code is called from a @MainActor context, say a method of a UIViewController , the callback crashes (dispatch_assert_queue failure) in Swift 6 mode because the Swift closure is inferred to be isolated to @MainActor but actually called on a background queue.

So my question is: how can I annotate the Swift closure to be non-isolated? I’ve tried all kinds of syntaxes but nothing works.

At least in Swift 5 mode, just putting @Sendable on the closure is enough:

Network().fetchResource { @Sendable (response) in
  // Process response
}

There's no type like nonisolated (Data) -> Void is there? So I can't think about how to spell it other than @Sendable.

1 Like

it works! Thank you so much! Do you know where this is documented? I found things related to Swift concurrency is really hard to find.

To be completely transparent I do not remember how I came upon this solution.