代码之家  ›  专栏  ›  技术社区  ›  user5273262

使用存储属性重写

  •  0
  • user5273262  · 技术社区  · 6 年前

    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' 
    

    (我想如果我重命名了该成员,也会出现同样的错误 coords coordinate

    因此,我尝试了以下方法:

    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

    3 回复  |  直到 6 年前
        1
  •  1
  •   farzadshbfn    6 年前

    你为什么要重新申报 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 坐标 为了便于阅读,我建议使用扩展名:

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

    然后分配给 super.init() 就像标题一样。

        2
  •  1
  •   Dávid Pásztor    6 年前

    你需要重新开始 _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()
        }
    }