用存储的 属性 覆盖

Overriding with a stored property

我这样扩展 MKPointAnnotation class:

class CustomPointAnnotation: MKPointAnnotation{

    let eventID: Int
    let coords: CLLocationCoordinate2D
    var title: String? // error here
    let location:String

    init(eventID:Int, coords:CLLocationCoordinate2D, location:String, title:String?) {

        self.eventID = eventID
        self.coords = coords
        self.title = title
        self.location = location

        super.init()
    }
}

我得到一个错误:

Cannot override with a stored property 'title' 

(我想如果我将成员 coords 重命名为 coordinate 也会得到同样的错误)。

所以,我尝试了以下方法:

private var _title:String?

override var title: String? {
        get { return _title }
        set { _title = newValue }
    }

但是,当我在 init 的正文中添加 self.title = title 时,我得到:

'self' used in property access 'title' before 'super.init' call

如果我在上面移动 super.init(),我会得到两种错误:

  1. Property 'self.eventID' not initialized at super.init call (1 error)
  2. Immutable value 'self.coords' may only be initialized once (repeated for every property)

声明 title 属性 的正确方法是什么?有没有可能覆盖它?我发现了很多关于这个主题的问题,但是没有扩展内置 class 的例子。感谢任何帮助

您需要在初始化程序中设置 _title 而不是 title。由于这是title的私人后盾属性,因此当您第一次访问title时,它将具有正确的值,而无需直接设置它。

class CustomPointAnnotation: MKPointAnnotation {

    let eventID: Int
    let coords: CLLocationCoordinate2D
    let location:String

    private var _title:String?

    override var title: String? {
        get { return _title }
        set { _title = newValue }
    }

    init(eventID:Int, coords:CLLocationCoordinate2D, location:String, title:String?) {

        self.eventID = eventID
        self.coords = coords
        self._title = title
        self.location = location

        super.init()
    }
}

为什么需要再次重新声明var title: String??通过继承 MKPointAnnotation,您已经可以访问 title。 (coords 也是如此)。

你可以直接设置标题,在super.init()

之后
init(eventID: Int, coords: CLLocationCoordinate2D, location: String, title: String?) {

        self.eventID = eventID
        self.coords = coords
        self.location = location

        super.init()
        self.title = title
    }

如果您想将 coordiante 重命名为 coords 以提高可读性,我建议使用扩展名:

extension CustomPointAnnotation {
    var coords: CLLocationCoordinate2D {
        get { return coordinate }
        set { coordinate = newValue }
    }
}

并在 super.init() 之后赋值,就像标题一样。