本文介绍了理解快速语言中的去初始化和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个类:基类和子类如下:

Let's say I have two classes: Base class and sub class like this:

class Base{
    var name: String?
    init() {
       name = "The base class"
    }

    deinit {
       println("call Deinitialization in base class")
       name = nil
    }
}

class Sub: Base{
    var subName: String?
    init() {
     super.init()
     subName = "The sub class"
    }

    deinit {
       println("call Deinitialization in sub class")
       subName = nil
       // does it really call super.deinit() ?
       // or assign name = nil ?
    }
}

当调用子类的deinitializer时,是吗调用 super.deinit() name 变量分配给nil?或者我必须在子类的deinitializer中手动分配?

When the deinitializer of sub class is called, does it call super.deinit() to assign name variable to nil? Or I have to assign by hand in deinitializer of subclass?

推荐答案

您可以选择 deinit 在你的子类中。

You can optionally have a deinit inside your subclass.

如果你这样做

    let x = Sub()

你会看到第一个 deinit 被叫是 Sub()里面的那个,之后是 base deinit 被调用。所以是的, super.deinit()被调用但是在子类之后。

you'll see that first the deinit called is the one inside Sub() then after, base deinit is called. So yes the super.deinit() is called but after the subclass.

这本书也说了(第286页) ):

Also the book says (page 286):

摘录自:Apple Inc. Swift编程语言。iBooks。

Excerpt From: Apple Inc. "The Swift Programming Language." iBooks. https://itun.es/us/jEUH0.l

这篇关于理解快速语言中的去初始化和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 05:39