AnyHashable and Sendable keys

Hi,

How could I pass a [AnyHashable, any Sendable] dictionary between 2 different actors?

I would need it to be Sendable, but AnyHashable is not Sendable, and any Hashable & Sendable does not conform to Hashable.

Would I have to box all keys, even if all keys have Sendable types (let's say String and Int)?

Thanks!

5 Likes

Asking myself the same question. Somehow AnyHashable would have to be Sendable if the type thats passed is Sendable, but since the type is erased, that wouldn't work out. The only option would be to have something like AnySendableHashable type, but that in turn would require us to box the keys which would look weird at the call site, since own types cannot get that compiler magic that AnyHashable has.

You can write another wrapper that does that for you:

struct AnyHashableAndSendable: @unchecked Sendable, Hashable {
    private let wrapped: AnyHashable
    
    init(wrapped: some Hashable & Sendable) {
        self.wrapped = .init(wrapped)
    }
}

The proper solution would require Swift to support any Hashable but I haven't seen any recent discussions about full support for this.

2 Likes

Smart, will try that out!
Yeah, I guess existentials would have to actually conform to the protocol itself to make that work.