0

我以这种方式扩展了MKPointAnnotation课程:

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' 

(我想如果我将成员重命名为 ,我会得到同样的错误coordscoordinate

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

private var _title:String?

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

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

'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财产申报的正确方法是什么?有没有可能覆盖它?我发现了很多关于这个主题的问题,但没有扩展内置类的例子。任何帮助表示赞赏

4

2 回答 2

1

为什么需要重新声明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
    }

如果您想重命名coordiantecoords便于阅读,我建议使用扩展名:

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

super.init()并像标题一样分配它。

于 2019-01-29T10:09:54.963 回答
1

您需要_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()
    }
}
于 2019-01-29T09:59:20.707 回答