关于ios:将Double转换为CLLocationDegrees [SWIFT]

Convert Double to CLLocationDegrees [SWIFT]

我正在尝试将两个数组转换为CLLocationDegrees,然后从那里将它们合并到一个数组(CLLocationCoordinate2D)中。

所以让我们从头开始:

我有两个从Firestore收到的Double类型的数组。 (一个带有经度,另一个带有经度)。我正在尝试将这些数组转换为CLLocationDegrees,然后将它们合并到一个应该为CLLocationCoordiante2D类型的数组中。

在代码的顶部(在该类中),我是这样的:

1
2
3
4
var latitude:[Double] = []
var longitude:[Double] = []

var locations: [CLLocationCoordinate2D] = []

在viewDidLoad之后,我创建了一个看起来像这样的函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
    }
}

我得到的警告是:

Cast from '[Double]' to unrelated type 'CLLocationDegrees' (aka 'Double') always fails

如果我打印"位置",它将返回:

[0, 0]

有人知道如何解决此问题吗?请告诉我。
如果您不喜欢这里,请至少在评论中写下原因。


请仔细阅读警告。

latitudelongitude都是数组,并且CLLocationCoordinate2D init方法期望一个latitude和一个longitude

您可以使用zipmap创建坐标数组

1
2
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)}

或更短的

1
locations = zip(latitude, longitude).map(CLLocationCoordinate2D.init)

如果条件失败,则断言行会导致致命错误。