ios - 从数组返回的属性创建常量

标签 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 中将它们表示为 map 上的各个位置。

希望这足够清楚,任何帮助都会受到赞赏。 谢谢。

最佳答案

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

这听起来是使用 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(latitude: 50.456781999999997, longitude: 14.578002), CLLocationCoordinate2D(latitude: 57.678654000000002, longitude: 17.890651999999999)]

MKAnnotation 无论如何都使用 CLLocationCooperative2D 作为它的坐标属性,所以这应该更容易。如果需要,您甚至可以在 map 函数中创建 MKAnnotations

使用结构体的示例:

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)

关于ios - 从数组返回的属性创建常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52294520/

相关文章:

objective-c - iOS 中的 ViewDidLoad 和 UINavigationController?

ios - Xamarin iOS 应用的自动化 CI 发布

iphone - 如何将 UIImage 转换为 NSData 或 CFDataRef?

Javascript:如何初始化二维数组

swift - 如何用Alamofire(帖子)上传图片?

ios - 在 App Store Connect 上找不到编辑版本。尝试使用 '--use_live_version true'

ios - ScrollView 内带有 TableView 的多个 View Controller

php - 数组中的字段未更新

c - 将字符附加到字符串数组中的字符串时出现段错误

arrays - 如何在 Swift 4 中将金字塔类型的字符串转换为 double 组