Accessing Underlying Memory of Data in C++ with New Span APIs

Hi everyone,

I just finished watching the Mixing C, C++ and Swift session from WWDC 2025, great stuff and exciting improvements!

One thing that stood out was the introduction of the new Span and MutableSpan types, which offer a type-safe way to access underlying contiguous memory of Foundation types like Array and InlineArray. This looks like a promising step for C++ interoperability, especially for performance-sensitive use cases.

While browsing the documentation afterward, I noticed that Span and MutableSpan are both marked as beta, which makes sense given how new they are.

However, I didn't see similar span-based APIs added for Data, which is often used interchangeably with Array<UInt8> and also exposes a contiguous memory buffer. Since Data is a common type when dealing with byte buffers across C, C++, and Swift boundaries, I was wondering:

Will Data also support the new Span/MutableSpan approach for accessing its underlying memory in a type-safe and idiomatic way from C++?

Or, if there's a different recommended pattern when working with Data in C++ interop scenarios going forward, I'd love to hear more about that.

Thanks in advance,

Harshal

4 Likes

Hi Harshal,

We did include Data in SE-0456 and SE-0467, adding Data.span, .bytes, .mutableSpan and .mutableBytes. It is implemented it swift-foundation (https://github.com/swiftlang/swift-foundation/pull/1276,) and it is mentioned in the Xcode 26 release notes.

We would like most interactions with Data to use these properties in the future.

4 Likes

Thanks @glessard !!

Thank you so much for the clarification and for pointing me to the Swift Foundation PR, really appreciate it!

I had checked the Apple Developer Documentation earlier for both Array and Data, and I could see the span API available for Array, but not for Data, which had me a bit confused. This clears things up!

It's great to know that the plan is to move most interactions with Data toward these new properties. Looking forward to adopting them as they become more widely integrated :slight_smile:

Thanks again!

Best,
Harshal

Is there a way for a C++ class to hold an instance of Data, retained and safely?

I have a C++ type that has a size() and a uint8_t* data() method and it needs to hold underlying Swift Data, but I haven't figured out a way to do that without copy. Especially because the unsafe bytes accessors are always just closures.

For the C++ class to own an instance of Data, it will need to own an Unmanaged of a box of a Data:

class DataBox {
  var data: Data
}

Span doesn't change this. I assume it's possible to make the usage from the C++ side more ergonomic than before, but I haven't tried that yet.