私はいくつかの異なるカスタムAnnotationオブジェクトを持っています。 これらはすべてMKAnnotationクラスとそのプロトコルを継承しています。異なるタイプのオブジェクトを持つmapView.annotations配列を調べるにはどうすればいいですか?
これは、それらの少なくとも2つがどのように見えるかで、そのうちのいくつかのより多くがあり、そして率直に言って、彼らはすべての非常によく似:
マイBaseAnnotationプロトコル:
import MapKit
/// Defines the shared stuff for map annotations
protocol BaseAnnotation: MKAnnotation {
var imageName: String { get }
var coordinate: CLLocationCoordinate2D { get set }
}
クエスト贈り主アノテーション:
import UIKit
import MapKit
class QuestGiverAnnotation: NSObject, BaseAnnotation {
var imageName = "icon_quest"
var questPin: QuestPin?
@objc var coordinate: CLLocationCoordinate2D
// MARK: - Init
init(forQuestItem item: QuestPin) {
self.questPin = item
if let lat = item.latitude,
lng = item.longitude {
self.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
} else {
self.coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
}
}
init(location: CLLocationCoordinate2D) {
self.coordinate = location
}
}
リソース注釈:
import UIKit
import MapKit
class ResourceAnnotation: NSObject, BaseAnnotation {
var imageName: String {
get {
if let resource = resourcePin {
return resource.imageName
} else {
return "icon_wood.png"
}
}
}
var resourcePin: ResourcePin?
@objc var coordinate: CLLocationCoordinate2D
var title: String? {
get {
return "Out of range"
}
}
// MARK: - Init
init(forResource resource: ResourcePin) {
self.resourcePin = resource
if let lat = resource.latitude,
lng = resource.longitude {
self.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
} else {
self.coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
}
}
init(location: CLLocationCoordinate2D) {
self.coordinate = location
}
}
私が言ったように、さらに2〜3つありますが、これらの2つとほぼ同じです。 なぜ私はそれらをこのようにしたのか聞かないでください...私はそれらのようにする必要がありました。
追加したすべてのマップ注釈をmapView.annotations
に表示すると問題が発生します。
私はfatal error: NSArray element failed to match the Swift Array Element type
を取得し、私はannotations
配列がdiferentタイプのオブジェクトで構成されているので、それはだが、私は特定の型のオブジェクトを取得dificultiesを持っていますことを理解しています。
これは私が配列から、私は必要な注釈を取得しようとしたのいずれかの方法、私は失敗しているユタ州:私は、この行のエラーを取得します
func annotationExistsAtCoordinates(lat: Double, long:Double) -> Bool{
var annotationExists = false
**let mapAnnotations: [Any] = self.annotations**
for item in mapAnnotations{
if let annotation = item as? QuestGiverAnnotation{
if annotation.coordinate.latitude == lat && annotation.coordinate.longitude == long{
annotationExists = true
}
//let annotation = self.annotations[i] as! AnyObject
}
}
return annotationExists
}
を:let mapAnnotations: [Any] = self.annotations
だから、私の質問fatal error: NSArray element failed to match the Swift Array Element type
を取得せずに、1つの配列から異なるタイプのオブジェクトを取得する方法は?
実行時またはコンパイル時にこのエラーが発生しますか? – ageektrapped
実行時です – SteBra