arraysiphoneswiftmkpolylinecllocationcoordinate2d

Not able to convert from Array data to CLLocationCoordinate2D in swift to draw a Polyline in mapview


I have array (coordinatesArray) of data which has double values like following.

(
    "-61.4149691",
    "42.9572076"
)
(
    "-61.4126004",
    "42.9572026"
)
(
    "-61.476674304",
    "42.9572032"
)

This is mapData

 (
        "-61.4149691",
        "42.9572076"
 )

So, I took a loop for converting each index data as latitude and longitude by converting as double.

 if let coordinatesArray = geoMetrys.value(forKey: "coordinates") as? NSArray {
    for mapData in coordinatesArray {
     print(mapData)

  let latitude = (mapData[0] as NSString).doubleValue
  let longitude = (mapData[1] as NSString).doubleValue

  var coordinatesToAppend: CLLocationCoordinate2D? = [latitude, longitude]

  var polyline = MKPolyline(coordinates: &coordinatesToAppend!, count: coordinatesArray.count)
 mapView.add(polyline)

But, its showing error while compiling time.

`Type 'Any' has no subscript members` for following lines
  let latitude = (mapData[0] as NSString).doubleValue
  let longitude = (mapData[1] as NSString).doubleValue

I have an array in that I have data of value as latitude and longitude. So, I am trying to draw a polyline in mapview with these values.

Can anyone suggest me where I am failing to achieve this?


Solution

  • In your code, the line

    if let coordinatesArray = geoMetrys.value(forKey: "coordinates") as? NSArray
    

    returns an array of type Any (i.e. [Any]). After that, when you use the for loop

    for mapData in coordinatesArray
    

    you are essentially looping over an array of Any where, in every iteration, an item (of type Any) is assigned to mapData. Now if this mapData is an array itself, you have to explicitly specify it as

    if let dataArray = mapData as? NSArray {
        let latitude = (dataArray[0] as NSString).doubleValue
        let longitude = (dataArray[1] as NSString).doubleValue
    }