在Swift中将MKMapPoint转换为NSValue

我想将MKMapPoint转换为NSValue。 在Objective-C中,我可以使用以下语句来完成:

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

我怎么能在Swift中做到这一点? 谢谢!

在Swift中是不可能的,但您仍然可以在ObjC中创建一个类别并在Swift项目中使用它

 // 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 

Swift中的用法:

 let mapValue = CGValue(MKMapPoint: ) let mapPoint = mapValue.MKMapPointValue(); 

遗憾的是,这在Swift中是不可能的。

尝试这个

  let mapPoint = MKMapPointForCoordinate(coordinate) let type = NSValue(MKCoordinate: coordinate).objCType // <- THIS IS IT let value = NSValue(bytes: unsafeAddressOf(mapPoint as! AnyObject), objCType: type);