I'm trying to convert two arrays into CLLocationDegrees, and from there merge them together into one array (CLLocationCoordinate2D
).
So let's start from the beginning:
I've two arrays of the type Double that I received from Firestore. (One with latitudes, and one with longitudes). I'm trying to convert these arrays into CLLocationDegrees and than merge them together to one array which should be of type CLLocationCoordiante2D
.
In the top of the code (in the class) I've this:
var latitude:[Double] = []
var longitude:[Double] = []
var locations: [CLLocationCoordinate2D] = []
And after the viewDidLoad I've created a function which looks like this:
func insertInMap()
{
if (CLLocationManager.locationServicesEnabled())
{
//WARNING BELOW
locations = [CLLocationCoordinate2D(latitude: latitude as! CLLocationDegrees, longitude: longitude as! CLLocationDegrees)]
print(locations)
//Insert the coordinates (In the correct order) into mapView.
//Draw a polyline between the coordinates
} else{
//Code here
}
}
The warning I get is:
Cast from '[Double]' to unrelated type 'CLLocationDegrees' (aka 'Double') always fails
If I print "locations" it returns:
[0, 0]
Anyone know how to solve this issue? Please let me know. And if you're here to dislike, atleast write the reason for it in the comments.
Please read the warning carefully.
Both latitude
and longitude
are arrays, and the CLLocationCoordinate2D
init
method expects one latitude
and one longitude
.
You could use zip
and map
to create the coordinate array
assert(latitude.count == longitude.count, "Both arrays must contain the same number of items")
locations = zip(latitude, longitude).map{CLLocationCoordinate2D(latitude: $0.0, longitude: $0.1)}
or even shorter
locations = zip(latitude, longitude).map(CLLocationCoordinate2D.init)
The assert line causes a fatal error if the condition fails.