Swift subclassing - how to override Init()

前端 未结 4 593
面向向阳花
面向向阳花 2021-02-01 13:40

I have the following class, with an init method:

class user {
  var name:String
  var address:String

  init(nm: String, ad: String) {
    name = nm
    address          


        
4条回答
  •  孤独总比滥情好
    2021-02-01 14:08

    In addition to Chuck's answer, you also have to initialize your new introduced property before calling super.init

    A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer. (The Swift Programming Language -> Language Guide -> Initialization)

    Thus, to make it work:

    init(nm: String, ad: String) {
        numberPriorVisits = 0  
        super.init(nm: nm, ad: ad) 
    }
    

    This simple initialization to zero could have been done by setting the property's default value to zero too. It's also encouraged to do so:

    var numberPriorVisits: Int = 0
    

    If you don't want such a default value it would make sense to extend your initializer to also set a new value for the new property:

    init(name: String, ads: String, numberPriorVisits: Int) {
        self.numberPriorVisits = numberPriorVisits
        super.init(nm: name, ad: ads)
    }
    

提交回复
热议问题