从结构访问信息

Accessing information from a struct

我正在尝试向地图添加注释,但无法访问存储在我的结构中的不同变量。我想设置名称、纬度和经度以提取变量餐厅中的元素。但是,在尝试实现纬度、经度和名称时,我收到错误消息。我将如何做到这一点,以便我可以访问我的变量中的任何餐厅的名称、纬度和经度。

这是我的代码。

import UIKit
import MapKit

struct PlacesOnMap {
var name: String
var latitude: Double
var longitude: Double

init(name: String, latitude: Double, longitude: Double) {
    self.name = name
    self.latitude = latitude
    self.longitude = longitude
}
}

class MapViewController: UIViewController {

var restaurants = [PlacesOnMap(name: "Pete's", latitude: -73.2455, longitude: 65.4443),
    PlacesOnMap(name: "Bake shop on 5th", latitude: 34.55555, longitude: 34.3333),
    PlacesOnMap(name: "Italian", latitude: -33.4444, longitude: 43.567)
]


@IBOutlet var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

}


func setRestaurantsAnnotations() {
    let places = MKPointAnnotation()
    places.coordinate = CLLocationCoordinate2D(latitude: restaurants.latitude, longitude: restaurants.longitude) //I get the error: Value of type '[PlacesOnMap]' has no member 'latitude' or 'longitude'
    places.title = restaurants.name //I get the error: Value of type '[PlacesOnMap]' has no member 'name'
    mapView.addAnnotation(places)
}
}

实际上这就是你想要做的:

restaurants.forEach { placeOnMap in
    let place = MKPointAnnotation()
    place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
    place.title = placeOnMap.name
    mapView.addAnnotation(place)
}

正如@matt在评论区提到的,restaurant是一个PlacesOnMap的数组。您的目标是将这些地点添加到地图中,因此您需要将这些地点中的每一个都转换为一个 CLLocationCoordinate2D 实例,然后将其添加到您的地图中。

或者,您可以这样做:

let places = restaurants.map { placeOnMap -> MKPointAnnotation in
    let place = MKPointAnnotation()
    place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
    place.title = placeOnMap.name
    return place
}
mapView.addAnnotations(places)

在这一个中,您将拥有的餐厅数组映射到 MKPointAnnotation 个实例数组中,然后您只需将此数组传递给 mapView