Closing and using UnsafeBufferPointer () in swift
I'm just trying to cast spells quickly.
I want to use the withUnsafeBufferPointer method on an array. In its simplest form, I can do something like this:
var aa:[UInt8] = [1,2,3,4,5,6,7,8]
var bb = aa.withUnsafeBufferPointer({$0.baseAddress})
I can also do this:
var bb = aa.withUnsafeBufferPointer({pointerVal in pointerVal.baseAddress})
however, I cannot do this without generating an error in xcode:
var bb = aa.withUnsafeBufferPointer({pointerVal in return pointerVal.baseAddress})
"Cannot convert the expression type '((ST5)->(ST5)->ST4)->((ST5)->ST4)->ST4' to type 'R'
The first two assignments imply an operator return
. If I express this explicitly, everything will fail. I can't come to terms with Apple's documentation. (see the chapter on closures in the Swift programming language). I want to include in this more complex closure that requires a return statement. What do I need to do for this?
source to share
If the closure does not contain just one expression, then you need to specify the parameters and return type:
var bb = aa.withUnsafeBufferPointer({pointerVal -> UnsafePointer<UInt8> in return pointerVal.baseAddress})
or annotate the variable so the compiler can infer the type:
var bb : UnsafePointer<UInt8> = aa.withUnsafeBufferPointer({pointerVal in return pointerVal.baseAddress})
But you should only use the pointer to the array buffer inside the closure. Storing a pointer in a variable like this is unsafe, because the array can be freed, the compiler doesn't know what it is referring to via bb
.
source to share