6

I want to convert an MKMapPoint to a NSValue. In Objective-C i can do it with the following statement:

MKMapPoint point = MKMapPointForCoordinate(location.coordinate);
NSValue *pointValue = [NSValue value:&point withObjCType:@encode(MKMapPoint)];

How can i do that in Swift? Thanks!

Leo
  • 91
  • 6
  • Does it need to be an MKMapPoint? There is an init for `CLLocationCoordinate2D` - `NSValue(MKCoordinate coordinate: CLLocationCoordinate2D)` – Grimxn Sep 08 '15 at 10:13
  • 1
    In this case it has to be MKMapPoint because the other extension i am integrating expects data to be in this format :( – Leo Sep 09 '15 at 08:35
  • I'm not sure there is a direct way, as `@encode` is not supported. See this post http://stackoverflow.com/questions/24456674/swift-equivalent-of-encode – Grimxn Sep 09 '15 at 08:50

3 Answers3

4

It isn't possible in Swift, but you can still create a category in ObjC and use it in your Swift project

// NSValue+MKMapPoint.h
@interface NSValue (MKMapPoint)

+ (NSValue *)valueWithMKMapPoint:(MKMapPoint)mapPoint;
- (MKMapPoint)MKMapPointValue;

@end


// NSValue+MKMapPoint.m
@implementation NSValue (MKMapPoint)

+ (NSValue *)valueWithMKMapPoint:(MKMapPoint)mapPoint {
    return [NSValue value:&mapPoint withObjCType:@encode(MKMapPoint)];
}

- (MKMapPoint)MKMapPointValue {
    MKMapPoint mapPoint;
    [self getValue:&mapPoint];
    return mapPoint;
}

@end

The usage in Swift:

let mapValue = CGValue(MKMapPoint: <your map point>)
let mapPoint = mapValue.MKMapPointValue();
Ondrej Stocek
  • 2,102
  • 1
  • 18
  • 13
1

I think Leo's answer isn't correct anymore, I managed to convert array of MKMapPoint to an array of CGPoint with the code below :

let polygonView = MKPolygonRenderer(overlay: overlay)
let polyPoints = polygonView.polygon.points() //returns [MKMapPoint]
var arrOfCGPoints : [CGPoint] = []
for i in 0..<polygonView.polygon.pointCount {
    arrOfCGPoints.append(polygonView.point(for: polyPoints[i])) //converts to CGPoint
    }
print(arrOfCGPoints)
//prints [(10896.74671715498, 10527.267575368285), (10830.46552553773, 10503.901612073183), (10741.784851640463, 10480.270403653383), (10653.04738676548, 10456.62348484993), (10566.442882657051, 10409.803505435586)]

And to NSValue :

ler someCgPoint = arrOfCGPoints[0]
var pointObj = NSValue(CGPoint: someCgPoint)
Vadim F.
  • 881
  • 9
  • 21
0

Sadly this is currently not possible in Swift.

Leo
  • 91
  • 6