0

I write an app in Swift and is bridging some Objective-C code. One of these classes has a method that looks like this: + (CLLocationCoordinate2D *)polylineWithEncodedString:(NSString *)encodedString;.

In Swift, it said this method returns a UnsafeMutablePointer<CLLocationCoordinate2D>. What I want is a Swift array of CLLocationCoordinate2D.

What obviously doesn't work, but I tried, is this:

let coordinates: [CLLocationCoordinate2D] = TheClass.polylineWithEncodedString(encodedString)

which will give me the following error:

'UnsafeMutablePointer<CLLocationCoordinate2D>' is not convertible to '[CLLocationCoordinate2D]'

Is it somehow possible to convert this UnsafeMutablePointer<CLLocationCoordinate2D> to a [CLLocationCoordinate2D]? Or should I take a different approach?

Viktor Nilsson
  • 1,673
  • 3
  • 14
  • 14
  • possible duplicate of [UnsafeMutablePointer in swift as replacement for properly sized C Array in Obj-C](http://stackoverflow.com/questions/25560751/unsafemutablepointer-in-swift-as-replacement-for-properly-sized-c-array-in-obj-c) – rakeshbs Jan 08 '15 at 12:18
  • This seems to be going the opposite way from [] to UnsafeMutablePointer<>, instead of UnsafeMutablePointer<> to []. – Viktor Nilsson Jan 08 '15 at 12:33
  • @ViktorNilsson: Do you know how *many* elements are returned via the pointer? Where is the array allocated and who is responsible for freeing it? – Passing a Swift array to be filled by the ObjC function (as in the referenced thread) would be easier in terms of memory management. – Martin R Jan 08 '15 at 12:47
  • @MartinR: Not easily, and then it is the memory management as you say. I guess I will have to try to pass the data in a different way. Do you have any idea what would be the best way to pass multiple structs, from ObjC, to Swift-code? – Viktor Nilsson Jan 08 '15 at 12:58

1 Answers1

0

You can just use the memory property of the UnsafeMutablePointer, which is the data behind the pointer. But keep in mind that UnsafeMutablePointer < CLLocationCoordinate2D > will return one CLLocationCoordinate2D, not an array, just as declared in the obj c function.

var coordinate: CLLocationCoordinate2D = TheClass.polylineWithEncodedString(encodedString).memory
Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58