以下是一个swift 类的初始化和反初始化。
其中:
1. 在convenience init中一定要调用 init函数,也就是说无论如何调用,类生成的时候init()函数必定执行
2. 将类指向nil时会调用deinit 函数, 该函数可以在类完全消失前做一些操作,比如写入文件
3. 一个类中可以有多个 convenience init,调用方法是由声明函数变量名称决定
import Foundation
class Sample
{
var a:Int?
init()// this is the init function, set a =0, will execute ervery time
{
a = 0
print("class inited a value set to\(a)")
}
convenienceinit(b:Int)//First convenience init function use a as variable, set the value to b
{
self.init()// this is needed
a = b
print("I wast inited by convenence init\(a)")
}
convenienceinit(c:Int)// Second convenience init function, swift allow 2 init function have the same kind of variable
{
self.init()
a = c*10
print("I wast inited by convenence init\(a)")
}
deinit
{
print("class deinited, a value was:\(a);")
}
}
var samClass, samClass2: Sample?
samClass = Sample(b: 1)//print 0 (init), 1 (conveneince init)
samClass = nil //print 1(deinit)
samClass2 = Sample() //print 0(init)
samClass2 = nil //print 0(deninit)
samClass = Sample(c: 1)//print 0(init), 10(convenience init)
samClass = nil //print 10(deinit)