Swift子类化-如何覆盖Init() [英] Swift subclassing - how to override Init()

查看:85
本文介绍了Swift子类化-如何覆盖Init()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有init方法的以下类:

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 = ad
  }
}

我正在尝试对该类进行子类化,但在super.init()部分上却不断出现错误:

I'm trying to subclass this class but I keep getting errors on the super.init() part:

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()方法并带有任何实际参数的要素类.他们所有的init都没有参数.

Apple's iBook has examples of subclassing, but none those feature classes that have an init() method with any actual arguments in it. All their init's are devoid of arguments.

那么,你怎么做到的?

推荐答案

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

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

指定的初始化程序必须确保所有属性 由其类引入的对象会在委托最多一个对象之前进行初始化 超类初始化器. (Swift编程语言->语言指南->初始化)

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) 
}

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

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)
}

这篇关于Swift子类化-如何覆盖Init()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆