Convert MKMapPoint to NSValue in Swift

I want to convert MKMapPoint to NSValue. In Objective-C, I can do this with the following statement:

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

How can I do this in Swift? Thanks!

+4
source share
4 answers

Unfortunately, in Swift this is currently not possible.

0
source

This is not possible in Swift, but you can 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

Usage in Swift:

let mapValue = CGValue(MKMapPoint: <your map point>)
let mapPoint = mapValue.MKMapPointValue();
+2
source

        let mapPoint = MKMapPointForCoordinate(coordinate)

        let type = NSValue(MKCoordinate: coordinate).objCType // <- THIS IS IT

        let value = NSValue(bytes: unsafeAddressOf(mapPoint as! AnyObject), objCType: type); 
0

, , MKMapPoint CGPoint :

    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)]
0

Source: https://habr.com/ru/post/1606383/


All Articles