MKAnnotation Swift
我不确定如何用swift语言注释地图。 我不知道如何创buildNSObject类。 以下是我尝试的代码,但无法运行:
import Foundation import MapKit class MapPin : MKAnnotation { var mycoordinate: CLLocationCoordinate2D var mytitle: String var mysubtitle: String func initMapPin (coordinate: CLLocationCoordinate2D!, title: String!, subtitle: String!) { mycoordinate = coordinate mytitle = title mysubtitle = subtitle } }
- Swift中的所有初始化方法都必须是“init”
- MKAnnotation要求对象从NSObjectProtocolinheritance。 要做到这一点,你应该让你的类inheritanceNSObject
- 你应该声明你的属性来匹配那些MKAnnotation协议
- 你不应该声明你的参数为隐式解开的选项,除非你真的必须这样做。 让编译器检查是否有零,而不是抛出运行时错误。
这给你的结果:
class MapPin : NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var title: String? var subtitle: String? init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) { self.coordinate = coordinate self.title = title self.subtitle = subtitle } }