[英]How to acces a value in a dictionary of tuples swift 4
我试图访问分配给键的某些值的元组字典。 一旦我填充了数据,我似乎无法找到如何访问字典。
这是字典。
var eventAnnotation = [(eventTitle: String,
eventLocation: String,
eventLat: CLLocationDegrees,
eventLong: CLLocationDegrees)]()
这就是我试图访问它的方式。
for event in eventAnnotation {
let annotation = MKPointAnnotation()
annotation.title = eventAnnotation.eventTitle
annotation.subtitle = eventAnnotation.eventLocation
annotation.coordinate = CLLocationCoordinate2D(latitude: eventAnnotation.eventLat, longitude: eventAnnotation.eventLong)
eventMap.addAnnotation(annotation)
}
对不起,如果这很简单!
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.