var eventAnnotation = [(eventTitle: String,
eventLocation: String,
eventLat: CLLocationDegrees,
eventLong: CLLocationDegrees)]()
上面是不是一个字典,而是一个元组数组,但是是的,它是一种方式,你似乎这样做是正确的,其他遍历数组的方法:
1) 使用Array.forEach
eventAnnotation.forEach { event in
let annotation = MKPointAnnotation()
annotation.title = event.eventTitle
annotation.subtitle = event.eventLocation
annotation.coordinate = CLLocationCoordinate2D(latitude: event.eventLat, longitude: event.eventLong)
eventMap.addAnnotation(annotation)
}
2) 使用Array.map
let annotations: [MKAnnotation] = eventAnnotation.map { event in
let annotation = MKPointAnnotation()
annotation.title = event.eventTitle
annotation.subtitle = event.eventLocation
annotation.coordinate = CLLocationCoordinate2D(latitude: event.eventLat, longitude: event.eventLong)
annotation)
return annotation
}
eventMap.addAnnotations(annotations)
等等……
如果您正在查找字典,您可以通过以下方式查找字典:
// Initialize an empty dictionary
var dict: [String : (eventTitle: String, eventLocation: String, eventLat: CLLocationDegrees, eventLong: CLLocationDegrees)] = [:]
// Add an item to dictionary
dict["EventId-1"] = ("Event Title 1", "Event Location 1", 53.0, 27.0)
// Add another item to dictionary
dict["EventId-2"] = (eventTitle: "Event Title 2",
eventLocation: "Event Location",
eventLat: 53.0,
eventLong: 27.0)
以下是遍历字典的方法:
for (key, event) in dict {
let annotation = MKPointAnnotation()
annotation.title = event.eventTitle
annotation.subtitle = event.eventLocation
annotation.coordinate = CLLocationCoordinate2D(latitude: event.eventLat, longitude: event.eventLong)
eventMap.addAnnotation(annotation)
}
Update-1 以下是为某些键过滤字典的方法:
1) 遍历整个字典并搜索所需的键:
for (key, event) in dict {
guard (key == "Event1" || key == "Event2") else { continue }
let annotation = MKPointAnnotation()
annotation.title = event.eventTitle
annotation.subtitle = event.eventLocation
annotation.coordinate = CLLocationCoordinate2D(latitude: event.eventLat, longitude: event.eventLong)
eventMap.addAnnotation(annotation)
}
2) 检查字典中是否存在某个键:
if let event = dict["Event1"] {
let annotation = MKPointAnnotation()
annotation.title = event.eventTitle
annotation.subtitle = event.eventLocation
annotation.coordinate = CLLocationCoordinate2D(latitude: event.eventLat, longitude: event.eventLong)
eventMap.addAnnotation(annotation)
}