malena
malena

Reputation: 948

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

Upvotes: 3

Views: 3722

Answers (2)

Den Jo
Den Jo

Reputation: 421

Swift 3

struct GradientPoint {
  var location: CGFloat
  var color: UIColor
}

gradientPoints.flatMap { $0.color.cgColor.components }.flatMap { $0 }

Upvotes: 0

luk2302
luk2302

Reputation: 57124

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)

Upvotes: 2

Related Questions