1

I'm having a brain cramp this afternoon. This should be easy.

I did read the docs.

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html

It's easy to convert single instances of Float <> CGFloat but I'm looking for a fast method to cast a LARGE array > 500,000 elements of [Float] to [CGFloat].

var sphereRadiusFloat:[Float] = [0.0,1.0,2.0]
var sphereRadiusCGFloat:[CGFloat] = []

sphereRadiusCGFloat = sphereRadiusFloat as CGFloat

The error is

CGFloat is not convertible to [CGFloat]

I also tried

sphereRadiusCGFloat = CGFloat(sphereRadiusFloat)

which gives error

Could not find an overload operator for 'init' that accepts supplied arguments.

  • The problem here is that you are trying to convert a type that is a array of CGFloat to just CGFloat, the method that @Leonardo Savio Dabus show you is a very elegant method new in swift, however the other way to do this would be looping all the elements in the array and converting one at the time – Icaro May 22 '15 at 01:56
  • Thanks, I was hoping to avoid looping, and going the `Anyobject` route and like the map solution from @Leonardo Savio Dabus as it is `perl-ish`. I'm a fan of those powerful one-liners. – μολὼν.λαβέ May 22 '15 at 02:01
  • 2
    Internally, of course, `map` is looping, you just don't see the loop explicitly. It may be no faster. – vacawama May 22 '15 at 02:09
  • 1
    i benchmarked a loop and map, for this particular call, the map vectorization is definitely faster by a substantial margin. to the down voters, you know what you can do with your worthless opinions. – μολὼν.λαβέ Jul 17 '15 at 13:52

1 Answers1

4

You can use map to do it as follow:

sphereRadiusCGFloat = sphereRadiusFloat.map{CGFloat($0)}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571