[swift-users] Why does the withUnsafeMutableBufferPointer closure take an inout parameter?

Guillaume Lessard glessard at tffenterprises.com
Sat Oct 14 12:42:00 CDT 2017

> On Oct 14, 2017, at 10:29, Braden Scothern via swift-users <swift-users at swift.org> wrote:
> There is a lot of value in these being mutating functions when working with C APIs that need a buffer for it to write to.
> If you have a collection and ensure it had allocated it's memory, you can then have the C API write directly into the collection's storage avoiding extra copy operations.
> I personally take advantage of this a lot. Because I'm wrapping a C library in Swift as part of my work.
> If this was changed to only non mutating functions, it still wouldn't be able to guarantee that the buffer isn't mutating the collection without always doing a deep copy. It is very easy to go from an UnsafeBufferPointer -> UnsafeMutableBufferPointer and have people change things.

The types wouldn’t change, just whether the method is marked `mutating`.

The reason I have doubts whether it’s worth it is that even if the implementation gets duplicated as non-mutating, it won’t prevent cases where a {*}BufferPointer needs to be a var: whenever it is passed into a generic MutableCollection context, it will need to be a var in order to be usable.
Is it worth it?

Guillaume Lessard

More information about the swift-users mailing list