[swift-users] Why does withUnsafePointer(to:) require a var argument?

Rick Mann rmann at latencyzero.com
Thu Apr 27 18:38:06 CDT 2017

> On Apr 27, 2017, at 01:48 , Alex Blewitt <alblue at apple.com> wrote:

> The let constant may not even be stored in a single place; if it's known to be constant it can be in-lined at the point of use and potentially unpacked and dead code elimination throw away the unused members, for example.
> If you want to pass in a let constant into the pointer, you can create a copy of it locally in a local variable and then use that instead. However this will be in the local scope, so the pointer isn't valid after it returns.

Ah, so this brings up another issue, then. Many of the calls in the C library take a pointer to some memory and hang on to it, filling it in at a later point (they make network requests). I've been doing it like this, and it's been working, but I wonder if this is fragile:

        self.dataBuffer = Data(count: kLGSImageDataSize)
        precondition(self.dataBuffer != nil, "Unable to allocate image buffer (\(kLGSImageDataSize) bytes)")
        var params = c_library_params_t()
        params.data_capacity = self.dataBuffer!.count
            { (inBuffer) -> Void in
                //  This call returns immediately, but assumes
                //  it can write to inBuffer later…
                self.request = c_library_call(&params, inBuffer)
        if self.request == nil
            //  Error

    var             dataBuffer:     Data?

Rick Mann
rmann at latencyzero.com

More information about the swift-users mailing list