Cast Any to Sendable

I'm continuing with the migration towards Swift 6. Within one of our libraries, I want to check whether a parameter object: Any? confirms to Sendable. I tried the most obvious one:

if let sendable = object as? Sendable {
}

But that results into the compiler error "Marker protocol 'Sendable' cannot be used in a conditional cast".

Is there an other way to do this?

That’s not surprising. Sendable is a marker protocol, which means it has no runtime presence, which means that a runtime type check isn’t feasible.

I’ve never seen folks bump into this before because a key goal of Swift concurrency is to have the compiler validate your concurrency at build time. Checking stuff at runtime kinda runs counter to that goal.

I don’t think there’s an obvious path forward here. I suspect you’ll have to take a step back and look at some bigger picture options, like converting this parameter to a generic or adding another routine that takes any Sendable.

If you can provide more details about the big picture, I’d be happy to offer further advice.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I have this issue, in the case where I get a userInfo dictionary from an OS API which is [String: Any], and I need to store it as a [String: any Sendable] to be able to fit it into my own code which is Sendable. What to do in this case?

For example there is a method func centralManager(_ cbCentralManager: CBCentralManager, didDiscover cbPeripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) from CBCentralManagerDelegate In our project we send advertisement data forward as we need it in the app to check if device is correct and to verify ids so that we will connect to right device.

I made a Sendable structure for storing scan data:

    public let peripheral: Peripheral
    /// A dictionary containing any advertisement and scan response data.
    public let advertisementData: [String : Any]
    /// The current RSSI of the peripheral, in dBm. A value of 127 is reserved and indicates the RSSI
    /// was not available.
    public let rssi: NSNumber
}

and I get warning: Stored property 'advertisementData' of 'Sendable'-conforming struct 'ScanData' has non-sendable type '[String : Any]'; this is an error in the Swift 6 language mode

So what to do here?

We want to make our projects Swift6 ready and also have strict concurrency, but default API we have are making this impossible on some parts.

Second example is usage of NSPRedicate in HKAnchoredObjectQuery initializer. It is not sendable, which also throws warning for Swift6.

Cast Any to Sendable
 
 
Q