我想轻松地在地图上获取 2 个或更多不同的对象类型。 Swift 2.0,我想使用协议。
我创建了一个这些对象也需要遵守的协议。我假设现在任何符合 PinProtocol 的项目本质上与 MKAnnotation 相同......只是更多!
protocol PinProtocol: MKAnnotation {
// stuff
}
我有 2 个班级,员工和客户
两者都符合 PinProtocol(还需要符合 MKAnnotation)
我知道这很有效,就像我这样设置我的班级一样,
class Client: NSObject, PinProtocol {
//var coordinate:CLLocationCoordinate2D // Leave out get doesn't conform to protocol warning as expected
}
因此,这告诉我 PinProtocol 正在按预期工作,因为需要遵守 PinProtocol 的项目也符合 MKAnnotation 协议。因为 MKAnnotation 需要坐标:CLLocationCooperative2D。
那么为什么我会遇到这个问题
let staffAndClients = [PinProtocol]()
mapView.addAnnotations(staffAndClients) // not allowed!
//mapView.addAnnotations(pins as! [MKAnnotation]) // also not allowed
错误是,无法将 [PinProtocol] 类型的值转换为预期参数 [MKAnnotation]
PinProtocol 不符合 MKAnnotation 所以应该可以工作。
但这样做效果很好
let staff = [Staff]()
mapView.addAnnotations(staff) // no problem
let clients = [Client]()
mapView.addAnnotations(clients) // no problem
我可以使用 AnyObject 解决这个问题,但为什么我不能使用 PinProtocol - 对我来说,这看起来更干净,并且是协议扩展的整个想法。
谢谢你的帮助。
Addit...
对于那些面临类似问题的人来说,我解决这个问题的方法是
var pins = [AnyObject]()
mapView.addAnnotations(pins as! [MKAnnotation])