Home Articles

Swift子类 - 如何覆盖Init()

Asked
Viewed 410 times
39

我有以下类,使用init方法:

class user {
  var name:String
  var address:String

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

我正在尝试子类化这个类,但我在 super.init() 部分一直遇到错误:

class registeredUser : user {
     var numberPriorVisits: Int

     // This is where things start to go wrong - as soon as I type 'init' it 
     // wants to autocomplete it for me with all of the superclass' arguments, 
     // and I'm not sure if those should go in there or not:
     init(nm: String, ad: String) {  
        // And here I get errors:
        super.init(nm: String, ad: String) 

     // etc....

Apple的iBook有子类化的例子,但没有那些具有 init() 方法的特征类,其中包含任何实际参数 . 他们所有的初学者都缺乏论据 .

那么,你是怎么做到的?

4 Answers

  • 34

    除了Chuck的答案之外,您还必须在调用super.init之前初始化新引入的属性

    指定的初始值设定项必须确保在委托一个超类初始化程序之前初始化其类引入的所有属性 . (Swift编程语言 - >语言指南 - >初始化)

    因此,为了使它工作:

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

    通过将属性的默认值设置为零,可以将此简单初始化为零 . 也鼓励这样做:

    var numberPriorVisits: Int = 0
    

    如果您不想要这样的默认值,那么将初始化程序扩展为为新属性设置新值也是有意义的:

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

    在swift 2.0和更高版本中它的工作原理如下(所有情况)

    init(newString:String) {
        super.init(string:newString)
        // Designed initialiser 
    }
    override init(someString: String) {
        super.init(mainString: someString)
        // Override initialiser when subclass some class 
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        // Some boilerplate code to handle error (needed when override)
    }
    convenience init(newString:String, withParameters:Dictionary<String,String>) {
        self.init(someString:newString)
        //Convenience initialiser 
    }
    
  • 3

    您将参数传递给初始化器,就像将参数传递给普通方法一样:

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

    作为参考,这可以在Swift语言指南的Designated and Convenience Initializers In Action部分中找到 .

  • 0

    您是否尝试将值设置为numberPriorVisits并将调用类型更改为super

    class user {
        var name:String
        var address:String
    
        init(nm: String, ad: String) {
            name = nm
            address = ad
        }
    }
    
    
    class registeredUser : user {
        var numberPriorVisits: Int;
    
        init(nm: String, ad: String) {
            self.numberPriorVisits = 0;
            super.init(nm: nm, ad: ad)
        }
    }
    

Related