3

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

malena
  • 798
  • 11
  • 26

2 Answers2

2

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)
luk2302
  • 55,258
  • 23
  • 97
  • 137
  • Hi luk, I explicitly declare colors as a CGFloat array, but I get , although different error message, still related message to passing the wrong argument type: "Cannot convert value of type '()' to expected argument type 'UnsafePointer'" – malena Dec 26 '15 at 20:13
  • @malena hm, what kind of error this time? For some reason my Playground compiles fine – luk2302 Dec 26 '15 at 20:14
  • @malena ah, yeah, forget about that one - the `NULL` is the problem – luk2302 Dec 26 '15 at 20:17
  • righto, i just discovered that the NULL is the problem myself. Thank you! – malena Dec 26 '15 at 20:19
  • 9
    doesn't answer the question: how do you pass in an Array to an UnsafePointer – johnrubythecat Oct 12 '16 at 17:52
  • @johnrubythecat I **did** answer the question in the sense that I proposed the actual solution to the problem. If that does not satisfy you, go ahead and post a question of your own. This post is obviously not the correct place for you. – luk2302 Oct 27 '16 at 13:30
  • 1
    It Just Works! Thanks! – Bobjt Nov 03 '16 at 00:52
0

Swift 3

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

gradientPoints.flatMap { $0.color.cgColor.components }.flatMap { $0 }
Den Jo
  • 413
  • 4
  • 10