Assuming I handle them correctly, what closure attributes can I safely bit cast in and away?

As the title says, what closure attributes can I safely bit cast in and away?

  • @escaping
  • @Sendable
  • @isolated(any)
  • any explicit isolation

And do any of these have irreversible drawbacks?
For example, does casting @isolated(any) away and in sequentially restore the stored isolation, or is it permanantly gone?

Well to not just blindly ask, I do know that @isolated(any) is bit cast able out and any explicit isolation is bit cast able both ways. I added them to the question to help other finders.

I don’t believe bitcasting closures is ever safe.

The language has some implicit conversions, like @escaping to non-@escaping and @Sendable to non-@Sendable for the safe combinations, so there is never a reason to unsafely bitcast closures.

2 Likes

MainActor.assumeIsolated does it, after checking its invariants: swift/stdlib/public/Concurrency/MainActor.swift at main · swiftlang/swift · GitHub

So presumably, at least casting away global actor annotations is safe so long as you enforce them manually.

You should not do things just because standard library code does them. The standard library is co-developed with the compiler, and it is not at all uncommon that we have to change that code in order to model something more explicitly.

4 Likes