理解快速语言中的去初始化和继承 [英] Understand deinitialization and inheritance in swift language
问题描述
假设我有两个类:基类和子类如下:
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):
您不能自己调用deinitializer。超类deinitializers由它们的子类继承,超类
deinitializer在子类
deinitializer实现的末尾自动调用。即使子类没有提供自己的deinitializer,超类deinitializers总是被
调用。
You are not allowed to call a deinitializer yourself. Superclass deinitializers are inherited by their subclasses, and the superclass deinitializer is called automatically at the end of a subclass deinitializer implementation. Superclass deinitializers are always called, even if a subclass does not provide its own deinitializer.
摘录自:Apple Inc. Swift编程语言。iBooks。 https://itun.es/us/jEUH0.l
Excerpt From: Apple Inc. "The Swift Programming Language." iBooks. https://itun.es/us/jEUH0.l
这篇关于理解快速语言中的去初始化和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!