MKAnnotation Swift

BDG*_*pps 35 iphone ios swift

我不确定如何用快速语言注释地图.我不知道如何创建NSObject类.以下是我尝试但无法运行的代码:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

dre*_*wag 92

  1. Swift中的所有初始化方法都必须简单地为"init"
  2. MKAnnotation要求对象继承自NSObjectProtocol.要做到这一点,你应该让你的类继承自NSObject
  3. 您应声明您的属性以匹配MKAnnotation协议的属性
  4. 除非确实需要,否则不应将参数声明为Implicitly Unwrapped Optionals.让编译器检查某些内容是否为nil而不是抛出运行时错误.

这会给你结果:

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
    }
}
Run Code Online (Sandbox Code Playgroud)