问题在于annotations 是MKAnnotation 的数组。但是这个协议只要求有一个coordinate 属性,但并不规定它是一个变量。注意协议中没有set:
public protocol MKAnnotation : NSObjectProtocol {
// Center latitude and longitude of the annotation view.
// The implementation of this property must be KVO compliant.
var coordinate: CLLocationCoordinate2D { get }
...
}
因此,当迭代MKMapView 的annotations(定义为MKAnnotation 的数组)时,它不知道您的坐标是变量还是常量,并生成该警告。
但是,让我们假设您的注释是MKPointAnnotation。在那个具体的注释类型中,coordinate 是一个变量,而不是一个常量。因此,您可以具体说明类型。例如:
for annotation in mapView.annotations {
if let annotation = annotation as? MKPointAnnotation {
annotation.coordinate = CLLocationCoordinate2D(latitude: 12.12121212, longitude: 14.312121121)
}
}
或者
mapView.annotations
.compactMap { $0 as? MKPointAnnotation }
.forEach { existingMarker in
existingMarker.coordinate = CLLocationCoordinate2D(latitude: 12.12121212, longitude: 14.312121121)
}
很明显,如果你定义了自己的符合MKAnnotation的注解类,显然:
将coordinate定义为变量,而不是常量;和
确保它是dynamic。
因此:
class MyAnnotation: NSObject, MKAnnotation {
dynamic var coordinate: CLLocationCoordinate2D
dynamic var title: String?
dynamic var subtitle: String?
// other properties unique to your annotation here
init(coordinate: CLLocationCoordinate2D, title: String? = nil, subtitle: String? = nil) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
super.init()
}
}
然后模式和上面一样,除了引用你的类,例如:
mapView.annotations
.compactMap { $0 as? MyAnnotation }
.forEach { existingMarker in
existingMarker.coordinate = CLLocationCoordinate2D(latitude: 12.12121212, longitude: 14.312121121)
}