根据数组返回的属性创建一个常量

时间:2018-09-12 11:53:31

标签: ios arrays swift mapkit

基本上,我有两个数组,一个包含纬度,另一个包含经度(显然,实际数组要长得多)。 即:

latArray = [50.456782, 57.678654]
longArray = [14.578002, 17.890652]

我需要使用for循环遍历这些数组,并创建一个对象,该对象将具有相应的纬度和经度,具体取决于数组的顺序。但是我真的不知道该怎么做。 即

firstPlace.latitude = 50.456782
firstPlace.longitude = 14.578002

secondPlace.latitude = 57.678654
secondPlace.longitude = 17.890652

我需要将它们作为单独的变量,因为我需要将它们传递到MKAnnotation中,以便以后可以在MKAnnotationView中表示为地图上的各个位置。

希望这很清楚,我们将为您提供帮助。 谢谢。

1 个答案:

答案 0 :(得分:0)

最好使用CLLocationCoordinate2D框架中的CoreLocation来表示坐标位置。

这听起来像是使用zip命令的好地方。

这里是一个例子:

let latArray = [50.456782, 57.678654]
let longArray = [14.578002, 17.890652]

let coordinates = zip(latArray, longArray).map { lat, lon in
    CLLocationCoordinate2D(latitude: lat, longitude: lon)
}

print(coordinates)

输出(略微整理):

  

[CLLocationCoordinate2D(纬度:50.456781999999997,经度:14.578002),CLLocationCoordinate2D(纬度:57.678654000000002,经度:17.890651999999999)]

MKAnnotation的坐标属性始终使用CLLocationCoordinate2D,因此应该更容易。如果需要,您甚至可以在地图功能中创建MKAnnotations

与struct一起使用的示例:

let latArray = [50.456782, 57.678654]
let longArray = [14.578002, 17.890652]

struct Place {
    var name: String
    var coordinate: CLLocationCoordinate2D
}

let places = zip(latArray, longArray).map { lat, lon in
    Place(name: "Some place",
          coordinate: CLLocationCoordinate2D(latitude: lat, longitude: lon))
}

print(places)