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

Martin R martinr448 at gmail.com
Tue Oct 10 02:50:21 CDT 2017

Thank you Howard for you response! However, I have a follow-up question:

Why are UnsafeMutableBufferPointer methods which modify not the buffer pointer itself, but only the pointed-to memory, mutating at all?

UnsafeMutable(Buffer)Pointer already have non-mutating subscript setters, which means that I can modify the pointed-to memory even if the buffer pointer itself is a constant. For example, this compiles and runs without problems:

    func foo(bufptr: UnsafeMutableBufferPointer<Int>) {
        let tmp = bufptr[0]
        bufptr[0] = bufptr[1]
        bufptr[1] = tmp

    var a = [1, 2, 3, 4, 5]
    a.withUnsafeMutableBufferPointer { foo(bufptr: $0) }

Doing the same with swapAt() does not compile:

    func bar(bufptr: UnsafeMutableBufferPointer<Int>) {
        bufptr.swapAt(0, 1)
        // error: cannot use mutating member on immutable value: 'bufptr' is a 'let' constant

which means that I have to use a variable copy:

    func bar(bufptr: UnsafeMutableBufferPointer<Int>) {
        var bufptr = bufptr
        bufptr.swapAt(0, 1)

So my "feeling" is that methods (like swapAt) which modify the pointed-to memory of an UnsafeMutableBufferPointer should be non-mutating. 

That would then also allow (coming back to my original question) that withUnsafeMutableBufferPointer() passes a _constant_ buffer pointer to the closure, and _might_ make the check at

obsolete (which verifies that the closure did not modify the pointer or length).

I am probably overlooking something, so please let me know where I am wrong!

Regards, Martin

> On 9. Oct 2017, at 01:15, Howard Lovatt <howard.lovatt at gmail.com> wrote:
> If it isn't an `inout` then it is a `let` not a `var` and hence you can't call mutating methods on it. There is no 'invar' in Swift, best you can do is `inout`.
>   -- Howard.
> On 9 October 2017 at 06:14, Martin R via swift-users <swift-users at swift.org> wrote:
> I wonder why the closure in the Array method
>     mutating func withUnsafeMutableBufferPointer<R>(_ body: (inout UnsafeMutableBufferPointer<Array.Element>) throws -> R) rethrows -> R
> takes an _inout_ parameter. The closure is called with a pointer to the contiguous array storage, and I fail to imagine an example where it makes sense to assign a new value to the parameter.
> Any insights are welcome!
> Regards, Martin
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

More information about the swift-users mailing list