初始化 – Swift子类化 – 如何覆盖Init()

前端之家收集整理的这篇文章主要介绍了初始化 – Swift子类化 – 如何覆盖Init()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下类,用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....

苹果的iBook有子类化的例子,但没有一个特性类有一个init()方法与任何实际参数。所有的初始化都没有参数。

那么,你怎么做呢?

除了Chuck的答案,你还必须在调用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)

因此,使它工作:

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)
}
原文链接:https://www.f2er.com/swift/320838.html

猜你在找的Swift相关文章