ios – 如何使用swift为多个注释设置数组

应该如何设置下面的数组.我试图在我的地图上添加多个注释.我能够在stackoverflow上找到下面的代码,但是他们没有展示如何设置数组.
var objects = [ 
                //how should the array be setup here 
              ]

for objecters in objects!{
    if let latit = objecters["Coordinates"]["Latitude"]{
        self.latitudepoint = latit as! String
        self.map.reloadInputViews()
    }
    else {
        continue
    }
    if let longi = objecters["Coordinates"]["Longitude"]{
        self.longitudepoint = longi as! String
        self.map.reloadInputViews()
    }
    else {
        continue
    }
    var annotation = MKPointAnnotation()
    var coord = CLLocationCoordinate2D(latitude: Double(self.latitudepoint)!,longitude: Double(self.longitudepoint)!)
    mapView.addAnnotation(annotation)
}

解决方法

你可以做,例如:
let locations = [
    ["title": "New York,NY","latitude": 40.713054,"longitude": -74.007228],["title": "Los Angeles,CA","latitude": 34.052238,"longitude": -118.243344],["title": "Chicago,IL","latitude": 41.883229,"longitude": -87.632398]
]

for location in locations {
    let annotation = MKPointAnnotation()
    annotation.title = location["title"] as? String
    annotation.coordinate = CLLocationCoordinate2D(latitude: location["latitude"] as! Double,longitude: location["longitude"] as! Double)
    mapView.addAnnotation(annotation)
}

或者,或者,使用自定义类型,例如:

struct Location {
    let title: String
    let latitude: Double
    let longitude: Double
}

let locations = [
    Location(title: "New York,latitude: 40.713054,longitude: -74.007228),Location(title: "Los Angeles,latitude: 34.052238,longitude: -118.243344),Location(title: "Chicago,latitude: 41.883229,longitude: -87.632398)
]

for location in locations {
    let annotation = MKPointAnnotation()
    annotation.title = location.title
    annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude,longitude: location.longitude)
    mapView.addAnnotation(annotation)
}

或者您可以使用map替换for循环:

let annotations = locations.map { location -> MKAnnotation in
    let annotation = MKPointAnnotation()
    annotation.title = location.title
    annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude,longitude: location.longitude)
    return annotation
}
mapView.addAnnotations(annotations)

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...