I'm trying to convert the Objective-C code in the MapKit MKPolygon
reference in Listing 6-9 into Swift.
When I call the function using the
init(coordinates:count:)
init function, I get the error:
Missing argument for parameter 'interiorPolygons' in call
When I call the function with the interiorPolygons argument, I get the error:
Extra argument in call
Here is the code that I am using.
var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()
points[0] = CLLocationCoordinate2DMake(41.000512, -109.050116)
points[1] = CLLocationCoordinate2DMake(41.002371, -102.052066)
points[2] = CLLocationCoordinate2DMake(36.993076, -102.041981)
points[3] = CLLocationCoordinate2DMake(36.99892, -109.045267)
var poly: MKPolygon = MKPolygon(points, 4)
poly.title = "Colorado"
theMapView.addOverlay(poly)
UPDATE:
points.withUnsafePointerToElements() { (cArray: UnsafePointer<CLLocationCoordinate2D>) -> () in
poly = MKPolygon(coordinates: cArray, count: 4)
}
seems to get rid of the compiler error, but still doesn't add an overlay.
The problems with:
are that it doesn't give the argument labels for the initializer and it's not passing
points
as a pointer.Change the line to:
(The
points.withUnsafePointerToElements...
version in your update will also work.)Also note that
var points: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()
creates an empty array. Doingpoints[0] = ...
should cause a run-time error since the array has no elements to begin with. Instead, add the coordinates to the array usingpoints.append()
:or just declare and initialize together:
If you still don't see the overlay, make sure you've implemented the
rendererForOverlay
delegate method (and set or connected the map view'sdelegate
property):Unrelated: Rather than calling the array
points
,coordinates
might be better becausepoints
implies the array might containMKMapPoint
structs which is what the(points:count:)
initializer takes as the first argument.