Search code examples
arraysswiftunsafe-pointers

how to pass a swift Array as UnsafePointer<T> argument in a function


I read that in order to pass a swift variable/constant to an argument that expects UnsafePointer can be done by using the 'inout' (ampersand) symbol prefixing the variable/constant. So in the following code, I want to pass the 'colors' array as "UnsafePointer' to the function CGGradientCreateWithColorComponents(), but I get a compiler error:

"& used with non-inout argument of type UnsafePointer"

See image below for visual.

So, the question is , how can I convert the swift array 'colors' into an UnsafePointer ?

thanks

enter image description here


Solution

  • Change your colors type to be explicitly [CGFloat]:

    var colors : [CGFloat] = [0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0]
    

    No need to deal with & or anything. But you have to actually pass in an array of CGFloat.

    And don't pass in NULL but nil:

    let gradient = CGGradientCreateWithColorComponents(baseSpace, colors, nil, 2)